-
Notifications
You must be signed in to change notification settings - Fork 10
/
encoding.go
274 lines (232 loc) · 7.32 KB
/
encoding.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package goa
import (
"encoding/gob"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"mime"
"sync"
"time"
)
type (
// DecoderFunc instantiates a decoder that decodes data read from the given io reader.
DecoderFunc func(r io.Reader) Decoder
// A Decoder unmarshals an io.Reader into an interface.
Decoder interface {
Decode(v interface{}) error
}
// ResettableDecoder is used to determine whether or not a Decoder can be reset and thus
// safely reused in a sync.Pool.
ResettableDecoder interface {
Decoder
Reset(r io.Reader)
}
// decoderPool smartly determines whether to instantiate a new Decoder or reuse one from a
// sync.Pool.
decoderPool struct {
fn DecoderFunc
pool *sync.Pool
}
// EncoderFunc instantiates an encoder that encodes data into the given writer.
EncoderFunc func(w io.Writer) Encoder
// An Encoder marshals from an interface into an io.Writer.
Encoder interface {
Encode(v interface{}) error
}
// The ResettableEncoder is used to determine whether or not a Encoder can be reset and
// thus safely reused in a sync.Pool.
ResettableEncoder interface {
Encoder
Reset(w io.Writer)
}
// encoderPool smartly determines whether to instantiate a new Encoder or reuse one from a
// sync.Pool.
encoderPool struct {
fn EncoderFunc
pool *sync.Pool
}
// HTTPDecoder is a Decoder that decodes HTTP request or response bodies given a set of
// known Content-Type to decoder mapping.
HTTPDecoder struct {
pools map[string]*decoderPool // Registered decoders
}
// HTTPEncoder is a Encoder that encodes HTTP request or response bodies given a set of
// known Content-Type to encoder mapping.
HTTPEncoder struct {
pools map[string]*encoderPool // Registered encoders
contentTypes []string // List of content types for type negotiation
}
)
// NewJSONEncoder is an adapter for the encoding package JSON encoder.
func NewJSONEncoder(w io.Writer) Encoder { return json.NewEncoder(w) }
// NewJSONDecoder is an adapter for the encoding package JSON decoder.
func NewJSONDecoder(r io.Reader) Decoder { return json.NewDecoder(r) }
// NewXMLEncoder is an adapter for the encoding package XML encoder.
func NewXMLEncoder(w io.Writer) Encoder { return xml.NewEncoder(w) }
// NewXMLDecoder is an adapter for the encoding package XML decoder.
func NewXMLDecoder(r io.Reader) Decoder { return xml.NewDecoder(r) }
// NewGobEncoder is an adapter for the encoding package gob encoder.
func NewGobEncoder(w io.Writer) Encoder { return gob.NewEncoder(w) }
// NewGobDecoder is an adapter for the encoding package gob decoder.
func NewGobDecoder(r io.Reader) Decoder { return gob.NewDecoder(r) }
// NewHTTPEncoder creates an encoder that maps HTTP content types to low level encoders.
func NewHTTPEncoder() *HTTPEncoder {
return &HTTPEncoder{
pools: make(map[string]*encoderPool),
}
}
// NewHTTPDecoder creates a decoder that maps HTTP content types to low level decoders.
func NewHTTPDecoder() *HTTPDecoder {
return &HTTPDecoder{
pools: make(map[string]*decoderPool),
}
}
// Decode uses registered Decoders to unmarshal a body based on the contentType.
func (decoder *HTTPDecoder) Decode(v interface{}, body io.Reader, contentType string) error {
now := time.Now()
defer MeasureSince([]string{"goa", "decode", contentType}, now)
var p *decoderPool
if contentType == "" {
// Default to JSON
contentType = "application/json"
} else {
if mediaType, _, err := mime.ParseMediaType(contentType); err == nil {
contentType = mediaType
}
}
p = decoder.pools[contentType]
if p == nil {
p = decoder.pools["*/*"]
}
if p == nil {
return nil
}
// the decoderPool will handle whether or not a pool is actually in use
d := p.Get(body)
defer p.Put(d)
return d.Decode(v)
}
// Register sets a specific decoder to be used for the specified content types. If a decoder is
// already registered, it is overwritten.
func (decoder *HTTPDecoder) Register(f DecoderFunc, contentTypes ...string) {
p := newDecodePool(f)
for _, contentType := range contentTypes {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
mediaType = contentType
}
decoder.pools[mediaType] = p
}
}
// newDecodePool checks to see if the DecoderFunc returns reusable decoders and if so, creates a
// pool.
func newDecodePool(f DecoderFunc) *decoderPool {
// get a new decoder and type assert to see if it can be reset
d := f(nil)
rd, ok := d.(ResettableDecoder)
p := &decoderPool{fn: f}
// if the decoder can be reset, create a pool and put the typed decoder in
if ok {
p.pool = &sync.Pool{
New: func() interface{} { return f(nil) },
}
p.pool.Put(rd)
}
return p
}
// Get returns an already reset Decoder from the pool or creates a new one if necessary.
func (p *decoderPool) Get(r io.Reader) Decoder {
if p.pool == nil {
return p.fn(r)
}
d := p.pool.Get().(ResettableDecoder)
d.Reset(r)
return d
}
// Put returns a Decoder into the pool if possible.
func (p *decoderPool) Put(d Decoder) {
if p.pool == nil {
return
}
p.pool.Put(d)
}
// Encode uses the registered encoders and given content type to marshal and write the given value
// using the given writer.
func (encoder *HTTPEncoder) Encode(v interface{}, resp io.Writer, accept string) error {
now := time.Now()
if accept == "" {
accept = "*/*"
}
var contentType string
for _, t := range encoder.contentTypes {
if accept == "*/*" || accept == t {
contentType = accept
break
}
}
defer MeasureSince([]string{"goa", "encode", contentType}, now)
p := encoder.pools[contentType]
if p == nil && contentType != "*/*" {
p = encoder.pools["*/*"]
}
if p == nil {
return fmt.Errorf("No encoder registered for %s and no default encoder", contentType)
}
// the encoderPool will handle whether or not a pool is actually in use
e := p.Get(resp)
if err := e.Encode(v); err != nil {
return err
}
p.Put(e)
return nil
}
// Register sets a specific encoder to be used for the specified content types. If an encoder is
// already registered, it is overwritten.
func (encoder *HTTPEncoder) Register(f EncoderFunc, contentTypes ...string) {
p := newEncodePool(f)
for _, contentType := range contentTypes {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
mediaType = contentType
}
encoder.pools[mediaType] = p
}
// Rebuild a unique index of registered content encoders to be used in EncodeResponse
encoder.contentTypes = make([]string, 0, len(encoder.pools))
for contentType := range encoder.pools {
encoder.contentTypes = append(encoder.contentTypes, contentType)
}
}
// newEncodePool checks to see if the EncoderFactory returns reusable encoders and if so, creates
// a pool.
func newEncodePool(f EncoderFunc) *encoderPool {
// get a new encoder and type assert to see if it can be reset
e := f(nil)
re, ok := e.(ResettableEncoder)
p := &encoderPool{fn: f}
// if the encoder can be reset, create a pool and put the typed encoder in
if ok {
p.pool = &sync.Pool{
New: func() interface{} { return f(nil) },
}
p.pool.Put(re)
}
return p
}
// Get returns an already reset Encoder from the pool or creates a new one if necessary.
func (p *encoderPool) Get(w io.Writer) Encoder {
if p.pool == nil {
return p.fn(w)
}
e := p.pool.Get().(ResettableEncoder)
e.Reset(w)
return e
}
// Put returns a Decoder into the pool if possible.
func (p *encoderPool) Put(e Encoder) {
if p.pool == nil {
return
}
p.pool.Put(e)
}