forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.go
42 lines (37 loc) · 954 Bytes
/
content.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package responsewriter
import (
"bufio"
"fmt"
"net"
"net/http"
"reflect"
"strings"
)
type ContentTypeWriter struct {
http.ResponseWriter
}
func (c ContentTypeWriter) Write(b []byte) (int, error) {
found := false
for k := range c.Header() {
if strings.EqualFold(k, "Content-Type") {
found = true
break
}
}
if !found {
c.Header().Set("Content-Type", http.DetectContentType(b))
}
return c.ResponseWriter.Write(b)
}
func ContentType(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writer := ContentTypeWriter{ResponseWriter: w}
handler.ServeHTTP(writer, r)
})
}
func (c ContentTypeWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacker, ok := c.ResponseWriter.(http.Hijacker); ok {
return hijacker.Hijack()
}
return nil, nil, fmt.Errorf("Upstream ResponseWriter of type %v does not implement http.Hijacker", reflect.TypeOf(c.ResponseWriter))
}