-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperation_params.go
332 lines (259 loc) · 6.84 KB
/
operation_params.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package goapi
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
ff "github.com/NaturalSelectionLabs/goapi/lib/flat-fields"
"github.com/NaturalSelectionLabs/jschema"
"github.com/xeipuuv/gojsonschema"
)
type paramsIn int
const (
inHeader paramsIn = iota + 1
inURL
inBody
)
type paramsInGuard struct{}
// InHeader is a flag that can be embedded into a struct to mark it
// as a container for request header parameters.
type InHeader struct{}
func (InHeader) inHeader() paramsInGuard { return struct{}{} }
// InURL is a flag that can be embedded into a struct to mark it
// as a container for request url parameters.
type InURL struct{}
func (InURL) inURL() paramsInGuard { return struct{}{} }
var tContext = reflect.TypeOf(new(context.Context)).Elem()
var tRequest = reflect.TypeOf((*http.Request)(nil))
type parsedParam struct {
in paramsIn
param reflect.Type
fields []*parsedField
isContext bool
isRequest bool
bodyValidator *gojsonschema.Schema
}
func (p *parsedParam) loadURL(qs url.Values) (reflect.Value, error) { //nolint: gocognit
val := reflect.New(p.param)
for _, f := range p.fields {
var (
fv reflect.Value
err error
)
if f.name == "path" {
vs, has := qs["*"]
if !has {
continue
}
fv, err = toValue(f.item, vs[0])
if err != nil {
return reflect.Value{}, fmt.Errorf("failed to parse url path param `%s`: %w", f.name, err)
}
} else if !f.InPath && f.slice {
vs, has := qs[f.name]
if has { //nolint: gocritic
fv = reflect.MakeSlice(f.sliceType, len(vs), len(vs))
} else if f.hasDefault {
fv = f.defaultVal
} else {
continue
}
for i, v := range vs {
val, err := toValue(f.item, v)
if err != nil {
return reflect.Value{}, fmt.Errorf("failed to parse url param `%s`: %w", f.name, err)
}
fv.Index(i).Set(val)
}
} else {
vs, has := qs[f.name]
if has { //nolint: gocritic
fv, err = toValue(f.item, vs[0])
if err != nil {
return reflect.Value{}, fmt.Errorf("failed to parse url path param `%s`: %w", f.name, err)
}
} else if f.required {
if !f.InPath {
return reflect.Value{}, fmt.Errorf("missing url query param `%s`", f.name)
}
return reflect.Value{}, fmt.Errorf("missing url path param `%s`", f.name)
} else if f.hasDefault {
fv = f.defaultVal
}
}
if f.ptr && !f.slice {
if fv.IsValid() {
c := reflect.New(f.item)
c.Elem().Set(fv)
f.flatField.Set(val, c)
}
} else {
f.flatField.Set(val, fv)
}
if err := f.validate(val); err != nil {
return reflect.Value{}, err
}
}
return val.Elem(), nil
}
func (p *parsedParam) loadHeader(h http.Header) (reflect.Value, error) {
qs := url.Values{}
// h to qs
for k, vs := range h {
for _, v := range vs {
qs.Add(toHeaderName(k), v)
}
}
return p.loadURL(qs)
}
func (p *parsedParam) loadBody(body io.Reader) (reflect.Value, error) {
val := reflect.New(p.param)
ref := val.Interface()
err := json.NewDecoder(body).Decode(&ref)
if err != nil {
return reflect.Value{}, fmt.Errorf("failed to parse json body: %w", err)
}
check, _ := p.bodyValidator.Validate(gojsonschema.NewGoLoader(ref))
if !check.Valid() {
return reflect.Value{}, fmt.Errorf("request body is invalid: %v", check.Errors())
}
return val.Elem(), nil
}
type parsedField struct {
name string // the normalized name of the field
item reflect.Type
flatField *ff.FlattenedField
ptr bool
slice bool
sliceType reflect.Type
required bool
InPath bool
hasDefault bool
defaultVal reflect.Value
schema *jschema.Schema
validator *gojsonschema.Schema
}
func (f *parsedField) validate(val reflect.Value) error {
v := f.flatField.Get(val).Interface()
res, _ := f.validator.Validate(gojsonschema.NewGoLoader(v))
if !res.Valid() {
return fmt.Errorf("param `%s` is invalid: %v", f.name, res.Errors())
}
return nil
}
func parseParam(s jschema.Schemas, path *Path, p reflect.Type) *parsedParam {
if p == tContext {
return &parsedParam{isContext: true}
}
if p == tRequest {
return &parsedParam{isRequest: true}
}
type InHeader interface {
inHeader() paramsInGuard
}
type InURL interface {
inURL() paramsInGuard
}
parsed := &parsedParam{param: p}
fields := []*parsedField{}
flat := ff.Parse(p)
switch reflect.New(p).Elem().Interface().(type) {
case InHeader:
parsed.in = inHeader
for _, f := range flat.Fields {
fields = append(fields, parseHeaderField(s, f))
}
case InURL:
parsed.in = inURL
for _, f := range flat.Fields {
fields = append(fields, parseURLField(s, path, f))
}
for _, n := range path.names {
has := false
for _, f := range fields {
if f.name == n {
has = true
}
}
if !has {
panic("expect to have path parameter for {" + n + "} in " + p.String())
}
}
default:
parsed.in = inBody
scm := s.ToStandAlone(s.DefineT(p))
validator, _ := gojsonschema.NewSchema(gojsonschema.NewGoLoader(scm))
parsed.bodyValidator = validator
}
parsed.fields = fields
return parsed
}
func parseHeaderField(s jschema.Schemas, flatField *ff.FlattenedField) *parsedField {
f := flatField.Field
parsed := parseField(s, flatField)
parsed.name = toHeaderName(f.Name)
parsed.name = tagName(f.Tag, parsed.name)
return parsed
}
func parseURLField(s jschema.Schemas, path *Path, flatField *ff.FlattenedField) *parsedField {
f := parseField(s, flatField)
t := flatField.Field
f.name = toPathName(t.Name)
if path.contains(f.name) {
if f.hasDefault {
panic("path parameter cannot have tag `default`, param: " + t.Name)
}
if f.slice {
panic("path parameter cannot be an slice, param: " + t.Name)
}
if !f.required {
panic("path parameter cannot be optional, param: " + t.Name)
}
f.InPath = true
} else {
f.name = toQueryName(t.Name)
}
f.name = tagName(t.Tag, f.name)
return f
}
func parseField(s jschema.Schemas, flatField *ff.FlattenedField) *parsedField {
f := flatField.Field
parsed := &parsedField{flatField: flatField, required: true}
t := f.Type
switch t.Kind() { //nolint: exhaustive
case reflect.Ptr, reflect.Slice:
parsed.ptr = true
default:
parsed.ptr = false
}
if t.Kind() == reflect.Ptr {
t = t.Elem()
parsed.required = false
}
if t.Kind() == reflect.Slice {
parsed.slice = true
parsed.sliceType = t
parsed.item = t.Elem()
parsed.required = false
} else {
parsed.item = t
}
parsed.schema = s.ToStandAlone(fieldSchema(s, f))
if _, ok := f.Tag.Lookup(string(jschema.JTagDefault)); ok {
parsed.required = false
parsed.hasDefault = true
parsed.defaultVal = reflect.ValueOf(parsed.schema.Default)
}
scm := parsed.schema
if !parsed.required {
s := &jschema.Schema{Defs: parsed.schema.Defs}
s.AnyOf = []*jschema.Schema{parsed.schema, {Type: jschema.TypeNull}}
scm = s
}
validator, _ := gojsonschema.NewSchema(gojsonschema.NewGoLoader(scm))
parsed.validator = validator
return parsed
}