forked from go-chi/chi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
content_type.go
53 lines (45 loc) · 1.22 KB
/
content_type.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
43
44
45
46
47
48
49
50
51
52
53
package render
import (
"net/http"
"strings"
"github.com/pressly/chi"
"golang.org/x/net/context"
)
// A ContentType is an enumeration of HTTP content types.
type ContentType int
const (
ContentTypePlainText = iota
ContentTypeHTML
ContentTypeJSON
ContentTypeEventStream
ContentTypeXML
)
func ParseContentType(next chi.Handler) chi.Handler {
return chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
var contentType ContentType
// Parse request Accept header.
fields := strings.Split(r.Header.Get("Accept"), ",")
if len(fields) > 0 {
switch strings.TrimSpace(fields[0]) {
case "text/plain":
contentType = ContentTypePlainText
case "text/html", "application/xhtml+xml":
contentType = ContentTypeHTML
case "application/json", "text/javascript":
contentType = ContentTypeJSON
case "text/event-stream":
contentType = ContentTypeEventStream
case "text/xml":
contentType = ContentTypeXML
default:
contentType = ContentTypeJSON
}
}
// Explicitly requested stream.
if _, ok := r.URL.Query()["stream"]; ok {
contentType = ContentTypeEventStream
}
ctx = context.WithValue(ctx, "contentType", contentType)
next.ServeHTTPC(ctx, w, r)
})
}