-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
101 lines (91 loc) · 2.12 KB
/
util.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"log"
"mime"
"net/http"
"sort"
"strconv"
"strings"
)
type Logger struct {
http.Handler
}
func NewLogger(handler http.Handler) *Logger {
return &Logger{handler}
}
func (l *Logger) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
lrw := &logResponseWriter{
ResponseWriter: rw,
status: http.StatusOK,
}
l.Handler.ServeHTTP(lrw, req)
log.Printf("%s %s %s %d %d %s", req.RemoteAddr, req.Method, req.URL.Path,
lrw.status, lrw.length, lrw.Header().Get("Content-Type"))
}
type logResponseWriter struct {
http.ResponseWriter
status int
length int64
}
func (rw *logResponseWriter) Write(b []byte) (int, error) {
n, err := rw.ResponseWriter.Write(b)
rw.length += int64(n)
return n, err
}
func (rw *logResponseWriter) WriteHeader(statusCode int) {
rw.status = statusCode
rw.ResponseWriter.WriteHeader(statusCode)
}
func selectContentType(req *http.Request, mediaTypes ...string) string {
var (
acceptValues = req.Header.Values("Accept")
acceptTypes []string
)
for _, v := range acceptValues {
acceptTypes = append(acceptTypes, strings.Split(v, ",")...)
}
sort.SliceStable(acceptTypes, func(i, j int) bool {
qi := parseMediaTypeQ(acceptTypes[i])
qj := parseMediaTypeQ(acceptTypes[j])
return qi > qj
})
for _, acceptType := range acceptTypes {
for _, mediaType := range mediaTypes {
if matchContentType(acceptType, mediaType) {
return mediaType
}
}
}
if len(mediaTypes) == 0 {
return ""
}
return mediaTypes[0]
}
func matchContentType(acceptValue, mediaType string) bool {
acceptType, _, err := mime.ParseMediaType(acceptValue)
switch {
case err != nil:
return false
case mediaType == acceptType:
return true
case acceptType == "*/*":
return true
case !strings.HasSuffix(acceptType, "/*"):
return false
default:
acceptType = strings.TrimSuffix(acceptType, "*")
return strings.HasPrefix(mediaType, acceptType)
}
}
func parseMediaTypeQ(acceptValue string) float64 {
_, params, _ := mime.ParseMediaType(acceptValue)
qval, ok := params["q"]
if !ok {
return 1.0
}
q, err := strconv.ParseFloat(qval, 64)
if err != nil {
return 1.0
}
return q
}