This repository has been archived by the owner on Jun 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
binder.go
67 lines (52 loc) · 1.37 KB
/
binder.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
package imp
import (
"encoding/json"
"encoding/xml"
"net/http"
"github.com/go-chi/chi"
"github.com/gorilla/schema"
)
var decoder = schema.NewDecoder()
type ParametersBinder struct{}
func (ParametersBinder) Bind(r *http.Request, dst interface{}) error {
src := map[string][]string{}
// Route parameters
if routeContext := chi.RouteContext(r.Context()); routeContext != nil {
for _, k := range routeContext.URLParams.Keys {
src[k] = append(src[k], routeContext.URLParam(k))
}
}
// Query
for k, v := range r.URL.Query() {
src[k] = append(src[k], v...)
}
return decoder.Decode(dst, src)
}
type JSONBinder struct{}
func (JSONBinder) Bind(r *http.Request, dst interface{}) error {
return json.NewDecoder(r.Body).Decode(dst)
}
type XMLBinder struct{}
func (XMLBinder) Bind(r *http.Request, dst interface{}) error {
return xml.NewDecoder(r.Body).Decode(dst)
}
type ContentNegotiationBinder struct {
JSONBinder JSONBinder
XMLBinder XMLBinder
ParametersBinder ParametersBinder
}
func (c ContentNegotiationBinder) Bind(r *http.Request, dst interface{}) error {
if r.ContentLength == 0 {
if r.Method == http.MethodGet || r.Method == http.MethodDelete {
return c.ParametersBinder.Bind(r, dst)
}
}
switch contentType(r) {
case "xml":
return c.XMLBinder.Bind(r, dst)
case "json":
fallthrough
default:
return c.JSONBinder.Bind(r, dst)
}
}