| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"net/http" |
| 5 |
"strings" |
| 6 |
) |
| 7 |
|
| 8 |
// ContentTypeWriter is an implementation of http.ResponseWriter that will detect the content type and set the |
| 9 |
// Content-Type and (optionally) Content-Disposition headers accordingly. |
| 10 |
// |
| 11 |
// It will always set a Content-Type based on http.DetectContentType, but will never send the "text/html" |
| 12 |
// content type. |
| 13 |
type ContentTypeWriter struct { |
| 14 |
w http.ResponseWriter |
| 15 |
filename string |
| 16 |
sniffed bool |
| 17 |
} |
| 18 |
|
| 19 |
// NewContentTypeWriter creates a new ContentTypeWriter |
| 20 |
func NewContentTypeWriter(w http.ResponseWriter, filename string) *ContentTypeWriter { |
| 21 |
return &ContentTypeWriter{w, filename, false} |
| 22 |
} |
| 23 |
|
| 24 |
func (w *ContentTypeWriter) Write(p []byte) (n int, err error) { |
| 25 |
if w.sniffed { |
| 26 |
return w.w.Write(p) |
| 27 |
} |
| 28 |
// Detect and set Content-Type header |
| 29 |
// Fix content types that we don't want to inline-render in the browser. In particular, |
| 30 |
// we don't want to render HTML in the browser for security reasons. |
| 31 |
contentType, _ := DetectContentType(p, w.filename) |
| 32 |
if strings.HasPrefix(contentType, "text/html") { |
| 33 |
contentType = strings.ReplaceAll(contentType, "text/html", "text/plain") |
| 34 |
} else if contentType == "application/octet-stream" { |
| 35 |
contentType = "" // Reset to let downstream http.ResponseWriter take care of it |
| 36 |
} |
| 37 |
if contentType != "" { |
| 38 |
w.w.Header().Set("Content-Type", contentType) |
| 39 |
} |
| 40 |
w.sniffed = true |
| 41 |
return w.w.Write(p) |
| 42 |
} |