-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.go
56 lines (41 loc) · 1.31 KB
/
decode.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
package httpencoder
import (
"io"
"net/http"
"sync"
)
func decode(bufferPool *sync.Pool, decoders map[string]Decoder, next http.Handler) http.Handler {
return http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
header := compactAndLow([]byte(request.Header.Get("Content-Encoding")))
if len(header) == 0 {
next.ServeHTTP(responseWriter, request)
return
}
bodyBuffer := bufferGet(bufferPool)
defer bufferPut(bufferPool, bodyBuffer)
if _, err := bodyBuffer.ReadFrom(request.Body); err != nil {
http.Error(responseWriter, "failed to read http request body", http.StatusBadRequest)
return
}
for iter := 0; iter < len(header); iter++ {
start := iter
for iter < len(header) && isAlpha(header[iter]) {
iter++
}
decoder, exist := decoders[string(header[start:iter])]
if !exist {
http.Error(responseWriter, "unsupported Content-Encoding", http.StatusUnsupportedMediaType)
return
}
content := bodyBuffer.Bytes()
bodyBuffer.Reset()
if err := decoder.Decode(request.Context(), bodyBuffer, content); err != nil {
http.Error(responseWriter, err.Error(), http.StatusInternalServerError)
return
}
}
request.Body = io.NopCloser(bodyBuffer)
request.Header.Del("Content-Encoding")
next.ServeHTTP(responseWriter, request)
})
}