-
-
Notifications
You must be signed in to change notification settings - Fork 583
Expand file tree
/
Copy pathrequest_binder.go
More file actions
71 lines (57 loc) · 1.54 KB
/
request_binder.go
File metadata and controls
71 lines (57 loc) · 1.54 KB
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
package binding
import (
"errors"
"fmt"
"net/http"
"strings"
"sync"
"github.com/gobuffalo/buffalo/internal/httpx"
)
var (
errBlankContentType = errors.New("blank content type")
)
// RequestBinder is in charge of binding multiple requests types to
// struct.
type RequestBinder struct {
lock *sync.RWMutex
binders map[string]Binder
}
// Register maps a request Content-Type (application/json)
// to a Binder.
func (rb *RequestBinder) Register(contentType string, fn Binder) {
rb.lock.Lock()
defer rb.lock.Unlock()
rb.binders[strings.ToLower(contentType)] = fn
}
// Exec binds a request with a passed value, depending on the content type
// It will look for the correct RequestTypeBinder and use it.
func (rb *RequestBinder) Exec(req *http.Request, value any) error {
rb.lock.Lock()
defer rb.lock.Unlock()
if ba, ok := value.(Bindable); ok {
return ba.Bind(req)
}
ct := httpx.ContentType(req)
if ct == "" {
return errBlankContentType
}
binder := rb.binders[ct]
if binder == nil {
return fmt.Errorf("could not find a binder for %s", ct)
}
return binder(req, value)
}
// NewRequestBinder creates our request binder with support for
// XML, JSON, HTTP and File request types.
func NewRequestBinder(requestBinders ...ContenTypeBinder) *RequestBinder {
result := &RequestBinder{
lock: &sync.RWMutex{},
binders: map[string]Binder{},
}
for _, requestBinder := range requestBinders {
for _, contentType := range requestBinder.ContentTypes() {
result.Register(contentType, requestBinder.BinderFunc())
}
}
return result
}