-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefaults.go
85 lines (65 loc) · 1.67 KB
/
defaults.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
package jsonapi
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
)
var contextType = reflect.TypeOf((*context.Context)(nil)).Elem()
var nilValue = reflect.ValueOf(nil)
// Defaults implements all the interfaces of this package in a default way.
//
// You can use this to compose custom behaviour on top.
var Defaults = &defaults{}
type defaults struct {
LogDomainErrors bool
}
func (d *defaults) Resolve(req *http.Request, t reflect.Type, pos int) (reflect.Value, error) {
if t.Implements(contextType) {
val := reflect.ValueOf(req.Context())
if !val.Type().AssignableTo(t) {
return val, fmt.Errorf("%w: context of type %v is not assignable to argument in pos #%d (%v)", ErrArgumentResolution, val.Type(), pos, t)
}
return val, nil
}
if !isStructWithJson(t) {
return nilValue, fmt.Errorf("%w: argument #%d (%v)", ErrArgumentUnsupported, pos, t)
}
ptr := false
if t.Kind() == reflect.Ptr {
ptr = true
t = t.Elem()
}
v := reflect.New(t).Interface()
err := json.NewDecoder(req.Body).Decode(&v)
if err == io.EOF {
return nilValue, ErrEmptyBody
}
if err != nil {
return nilValue, fmt.Errorf("%w: %s", ErrArgumentResolution, err.Error())
}
if ptr {
return reflect.Indirect(reflect.ValueOf(&v).Elem()).Elem(), nil
}
return reflect.Indirect(reflect.ValueOf(v).Elem()), nil
}
func (d *defaults) Validate(_ *http.Request) ([]*ErrorItem, error) {
return nil, nil
}
func isStructWithJson(t reflect.Type) bool {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return false
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if _, ok := f.Tag.Lookup("json"); ok {
return true
}
}
return false
}