ContentDispositionValue generates the content-disposition header value. It uses the following priorities: 1. By default, it uses the filename and extension from the URL. 2. If `filename` is provided, it overrides the URL filename. 3. If `contentType` is provided, it tries to determine the extension
(url, filename, ext, contentType string, returnAttachment bool)
| 30 | // 4. If `ext` is provided, it overrides any extension determined from the URL or header. |
| 31 | // 5. If the filename is still empty, it uses fallback stem. |
| 32 | func ContentDispositionValue(url, filename, ext, contentType string, returnAttachment bool) string { |
| 33 | // By default, let's use the URL filename and extension |
| 34 | _, urlFilename := filepath.Split(url) |
| 35 | urlExt := filepath.Ext(urlFilename) |
| 36 | |
| 37 | var rStem string |
| 38 | |
| 39 | // Avoid strings.TrimSuffix allocation by using slice operation |
| 40 | if urlExt != "" { |
| 41 | rStem = urlFilename[:len(urlFilename)-len(urlExt)] |
| 42 | } else { |
| 43 | rStem = urlFilename |
| 44 | } |
| 45 | |
| 46 | var rExt = urlExt |
| 47 | |
| 48 | // If filename is provided explicitly, use it |
| 49 | if len(filename) > 0 { |
| 50 | rStem = filename |
| 51 | } |
| 52 | |
| 53 | // If ext is provided explicitly, use it |
| 54 | if len(ext) > 0 { |
| 55 | rExt = ext |
| 56 | } else if len(contentType) > 0 && rExt == "" { |
| 57 | exts, err := mime.ExtensionsByType(contentType) |
| 58 | if err == nil && len(exts) != 0 { |
| 59 | rExt = exts[0] |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // If fallback is requested, and filename is still empty, override it with fallbackStem |
| 64 | if len(rStem) == 0 { |
| 65 | rStem = fallbackStem |
| 66 | } |
| 67 | |
| 68 | disposition := inlineDisposition |
| 69 | |
| 70 | // Create the content-disposition header value |
| 71 | if returnAttachment { |
| 72 | disposition = attachmentDisposition |
| 73 | } |
| 74 | |
| 75 | return fmt.Sprintf(contentDispositionsHeader, disposition, strings.ReplaceAll(rStem, `"`, "%22"), rExt) |
| 76 | } |