-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoder.go
48 lines (39 loc) · 1.04 KB
/
decoder.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
package gwf
import (
"encoding/json"
"net/http"
"github.com/gorilla/schema"
)
// Decoder defines a request decoder.
type Decoder interface {
// Decode decodes a request to a struct. req.PostForm is called in advanced.
Decode(obj interface{}, req *http.Request) error
}
// WithDecoder specifies the decoder which will be used.
func WithDecoder(d Decoder) RouteOptionFn {
return func(r *route) {
r.decoder = d
}
}
func newDecoder() Decoder {
return &defaultDecoder{
schemaDecoder: schema.NewDecoder(),
}
}
type defaultDecoder struct {
schemaDecoder *schema.Decoder
}
func (d *defaultDecoder) Decode(obj interface{}, req *http.Request) error {
if err := d.schemaDecoder.Decode(obj, req.Form); err != nil {
return err
}
contentType := req.Header.Get("Content-Type")
if contentType == "application/json" && req.ContentLength > 0 {
// erase all values in forms so that they won't overwrite parsed json values
jsonDecoder := json.NewDecoder(req.Body)
if err := jsonDecoder.Decode(obj); err != nil {
return err
}
}
return nil
}