-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpencoder.go
86 lines (70 loc) · 1.76 KB
/
httpencoder.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
package httpencoder
import (
"bytes"
"context"
"io"
"net/http"
"sync"
)
type (
// Encoder implements writer for http.ResponseWriter body.
Encoder interface {
// Encode encodes http.ResponseWriter body.
Encode(ctx context.Context, to io.Writer, from []byte) error
}
// Decoder implements reader for http.Request body.
Decoder interface {
// Decode decodes http.Request.Body.
Decode(ctx context.Context, to io.Writer, from []byte) error
}
)
const (
defaultQuality = 1000
)
// New returns net/http middleware for auto decode http.Request
// and/or auto encode http.ResponseWriter body based on provided Encoders/Decoders.
func New(encoders map[string]Encoder, decoders map[string]Decoder) func(next http.Handler) http.Handler {
bufferPool := &sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
return func(next http.Handler) http.Handler {
if len(decoders) != 0 {
next = decode(bufferPool, decoders, next)
}
if len(encoders) != 0 {
next = encode(bufferPool, encoders, next)
}
return next
}
}
func bufferGet(bufferPool *sync.Pool) *bytes.Buffer {
bodyBuffer, okay := bufferPool.Get().(*bytes.Buffer)
if !okay {
panic("httpencoder: unreachable code")
}
return bodyBuffer
}
func bufferPut(bufferPool *sync.Pool, buffer *bytes.Buffer) {
buffer.Reset()
bufferPool.Put(buffer)
}
func isAlpha(ch byte) bool {
return ch >= 'a' && ch <= 'z'
}
func compactAndLow(input []byte) []byte {
trueEnd := 0
for curPos := 0; curPos < len(input); curPos++ {
if input[curPos] == '\t' || input[curPos] == ' ' {
continue
}
if byte('A') <= input[curPos] && input[curPos] <= byte('Z') {
input[trueEnd] = input[curPos] - byte('A') + byte('a')
} else {
input[trueEnd] = input[curPos]
}
trueEnd++
}
return input[:trueEnd]
}