This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
/
binding.go
76 lines (64 loc) · 2.51 KB
/
binding.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
package binding
import (
"net/http"
"time"
"github.com/gobuffalo/buffalo/binding/decoders"
"github.com/gobuffalo/nulls"
"github.com/monoculum/formam"
)
var (
// MaxFileMemory can be used to set the maximum size, in bytes, for files to be
// stored in memory during uploaded for multipart requests.
// See https://golang.org/pkg/net/http/#Request.ParseMultipartForm for more
// information on how this impacts file uploads.
MaxFileMemory int64 = 5 * 1024 * 1024
// formDecoder (formam) that will be used across ContentTypeBinders
formDecoder = buildFormDecoder()
// BaseRequestBinder is an instance of the requestBinder, it comes with preconfigured
// content type binders for HTML, JSON, XML and Files, as well as custom types decoders
// for time.Time and nulls.Time
BaseRequestBinder = NewRequestBinder(
HTMLContentTypeBinder{
decoder: formDecoder,
},
JSONContentTypeBinder{},
XMLRequestTypeBinder{},
FileRequestTypeBinder{
decoder: formDecoder,
},
)
)
// buildFormDecoder that will be used in the package. This method adds some custom decoders for time.Time and nulls.Time.
func buildFormDecoder() *formam.Decoder {
decoder := formam.NewDecoder(&formam.DecoderOptions{
TagName: "form",
IgnoreUnknownKeys: true,
})
decoder.RegisterCustomType(decoders.TimeDecoderFn(), []interface{}{time.Time{}}, nil)
decoder.RegisterCustomType(decoders.NullTimeDecoderFn(), []interface{}{nulls.Time{}}, nil)
return decoder
}
// RegisterTimeFormats allows to add custom time layouts that
// the binder will be able to use for decoding.
func RegisterTimeFormats(layouts ...string) {
decoders.RegisterTimeFormats(layouts...)
}
// RegisterCustomDecoder allows to define custom decoders for certain types
// In the request.
func RegisterCustomDecoder(fn CustomTypeDecoder, types []interface{}, fields []interface{}) {
rawFunc := (func([]string) (interface{}, error))(fn)
formDecoder.RegisterCustomType(rawFunc, types, fields)
}
// Register maps a request Content-Type (application/json)
// to a Binder.
func Register(contentType string, fn Binder) {
BaseRequestBinder.Register(contentType, fn)
}
// Exec will bind the interface to the request.Body. The type of binding
// is dependent on the "Content-Type" for the request. If the type
// is "application/json" it will use "json.NewDecoder". If the type
// is "application/xml" it will use "xml.NewDecoder". The default
// binder is "https://github.com/monoculum/formam".
func Exec(req *http.Request, value interface{}) error {
return BaseRequestBinder.Exec(req, value)
}