-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.go
More file actions
62 lines (46 loc) · 1.43 KB
/
Copy pathdecode.go
File metadata and controls
62 lines (46 loc) · 1.43 KB
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
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)
_, err := bodyBuffer.ReadFrom(request.Body)
if 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 {
// not found decoder, pass it down without decoding
request.Body = io.NopCloser(bodyBuffer)
request.Header.Set("Content-Encoding", string(header[start:]))
next.ServeHTTP(responseWriter, request)
return
}
content := bodyBuffer.Bytes()
bodyBuffer.Reset()
err := decoder.Decode(request.Context(), bodyBuffer, content)
if err != nil {
http.Error(responseWriter, err.Error(), http.StatusInternalServerError)
return
}
}
request.Body = io.NopCloser(bodyBuffer)
request.Header.Del("Content-Encoding")
next.ServeHTTP(responseWriter, request)
})
}