-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
huma.go
1745 lines (1603 loc) · 51.4 KB
/
huma.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package huma provides a framework for building REST APIs in Go. It is
// designed to be simple, fast, and easy to use. It is also designed to
// generate OpenAPI 3.1 specifications and JSON Schema documents
// describing the API and providing a quick & easy way to generate
// docs, mocks, SDKs, CLI clients, and more.
//
// https://huma.rocks/
package huma
import (
"bytes"
"context"
"encoding"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/danielgtaylor/huma/v2/casing"
)
var errDeadlineUnsupported = fmt.Errorf("%w", http.ErrNotSupported)
var bodyCallbackType = reflect.TypeOf(func(Context) {})
var cookieType = reflect.TypeOf((*http.Cookie)(nil)).Elem()
var fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
var stringType = reflect.TypeOf("")
// SetReadDeadline is a utility to set the read deadline on a response writer,
// if possible. If not, it will not incur any allocations (unlike the stdlib
// `http.ResponseController`). This is mostly a convenience function for
// adapters so they can be more efficient.
//
// huma.SetReadDeadline(w, time.Now().Add(5*time.Second))
func SetReadDeadline(w http.ResponseWriter, deadline time.Time) error {
for {
switch t := w.(type) {
case interface{ SetReadDeadline(time.Time) error }:
return t.SetReadDeadline(deadline)
case interface{ Unwrap() http.ResponseWriter }:
w = t.Unwrap()
default:
return errDeadlineUnsupported
}
}
}
// StreamResponse is a response that streams data to the client. The body
// function will be called once the response headers have been written and
// the body writer is ready to be written to.
//
// func handler(ctx context.Context, input *struct{}) (*huma.StreamResponse, error) {
// return &huma.StreamResponse{
// Body: func(ctx huma.Context) {
// ctx.SetHeader("Content-Type", "text/my-type")
//
// // Write some data to the stream.
// writer := ctx.BodyWriter()
// writer.Write([]byte("Hello "))
//
// // Flush the stream to the client.
// if f, ok := writer.(http.Flusher); ok {
// f.Flush()
// }
//
// // Write some more...
// writer.Write([]byte("world!"))
// }
// }
// }
type StreamResponse struct {
Body func(ctx Context)
}
type paramFieldInfo struct {
Type reflect.Type
Name string
Loc string
Required bool
Default string
TimeFormat string
Explode bool
Schema *Schema
}
func findParams(registry Registry, op *Operation, t reflect.Type) *findResult[*paramFieldInfo] {
return findInType(t, nil, func(f reflect.StructField, path []int) *paramFieldInfo {
if f.Anonymous {
return nil
}
pfi := ¶mFieldInfo{
Type: f.Type,
}
if def := f.Tag.Get("default"); def != "" {
pfi.Default = def
}
var name string
var explode *bool
if p := f.Tag.Get("path"); p != "" {
pfi.Loc = "path"
name = p
pfi.Required = true
} else if q := f.Tag.Get("query"); q != "" {
pfi.Loc = "query"
split := strings.Split(q, ",")
name = split[0]
// If `in` is `query` then `explode` defaults to true. Parsing is *much*
// easier if we use comma-separated values, so we disable explode by default.
if slices.Contains(split[1:], "explode") {
pfi.Explode = true
}
explode = &pfi.Explode
} else if h := f.Tag.Get("header"); h != "" {
pfi.Loc = "header"
name = h
} else if c := f.Tag.Get("cookie"); c != "" {
pfi.Loc = "cookie"
name = c
if f.Type == cookieType {
// Special case: this will be parsed from a string input to a
// `http.Cookie` struct.
f.Type = stringType
}
} else {
return nil
}
if f.Type.Kind() == reflect.Pointer {
// TODO: support pointers? The problem is that when we dynamically
// create an instance of the input struct the `params.Every(...)`
// call cannot set them as the value is `reflect.Invalid` unless
// dynamically allocated, but we don't know when to allocate until
// after the `Every` callback has run. Doable, but a bigger change.
panic("pointers are not supported for path/query/header parameters")
}
pfi.Schema = SchemaFromField(registry, f, "")
var example any
if e := f.Tag.Get("example"); e != "" {
example = jsonTagValue(registry, f.Type.Name(), pfi.Schema, f.Tag.Get("example"))
}
if example == nil && len(pfi.Schema.Examples) > 0 {
example = pfi.Schema.Examples[0]
}
// While discouraged, make it possible to make query/header params required.
if r := f.Tag.Get("required"); r == "true" {
pfi.Required = true
}
pfi.Name = name
if f.Type == timeType {
timeFormat := time.RFC3339Nano
if pfi.Loc == "header" {
timeFormat = http.TimeFormat
}
if f := f.Tag.Get("timeFormat"); f != "" {
timeFormat = f
}
pfi.TimeFormat = timeFormat
}
if !boolTag(f, "hidden", false) {
desc := ""
if pfi.Schema != nil {
// If the schema has a description, use it. Some tools will not show
// the description if it is only on the schema.
desc = pfi.Schema.Description
}
// Document the parameter if not hidden.
op.Parameters = append(op.Parameters, &Param{
Name: name,
Description: desc,
In: pfi.Loc,
Explode: explode,
Required: pfi.Required,
Schema: pfi.Schema,
Example: example,
})
}
return pfi
}, false, "Body")
}
func findResolvers(resolverType, t reflect.Type) *findResult[bool] {
return findInType(t, func(t reflect.Type, path []int) bool {
tp := reflect.PointerTo(t)
if tp.Implements(resolverType) || tp.Implements(resolverWithPathType) {
return true
}
return false
}, nil, true)
}
func findDefaults(registry Registry, t reflect.Type) *findResult[any] {
return findInType(t, nil, func(sf reflect.StructField, i []int) any {
if d := sf.Tag.Get("default"); d != "" {
if sf.Type.Kind() == reflect.Pointer && sf.Type.Elem().Kind() == reflect.Struct {
panic("pointers to structs cannot have default values")
}
s := registry.Schema(sf.Type, true, "")
return convertType(sf.Type.Name(), sf.Type, jsonTagValue(registry, sf.Name, s, d))
}
return nil
}, true)
}
type headerInfo struct {
Field reflect.StructField
Name string
TimeFormat string
}
func findHeaders(t reflect.Type) *findResult[*headerInfo] {
return findInType(t, nil, func(sf reflect.StructField, i []int) *headerInfo {
// Ignore embedded fields
if sf.Anonymous {
return nil
}
header := sf.Tag.Get("header")
if header == "" {
header = sf.Name
}
timeFormat := ""
if sf.Type == timeType {
timeFormat = http.TimeFormat
if f := sf.Tag.Get("timeFormat"); f != "" {
timeFormat = f
}
}
return &headerInfo{sf, header, timeFormat}
}, false, "Status", "Body")
}
type findResultPath[T comparable] struct {
Path []int
Value T
}
type findResult[T comparable] struct {
Paths []findResultPath[T]
}
func (r *findResult[T]) every(current reflect.Value, path []int, v T, f func(reflect.Value, T)) {
if len(path) == 0 {
f(current, v)
return
}
current = reflect.Indirect(current)
if current.Kind() == reflect.Invalid {
// Indirect may have resulted in no value, for example an optional field
// that's a pointer may have been omitted; just ignore it.
return
}
switch current.Kind() {
case reflect.Struct:
r.every(current.Field(path[0]), path[1:], v, f)
case reflect.Slice:
for j := 0; j < current.Len(); j++ {
r.every(current.Index(j), path, v, f)
}
case reflect.Map:
for _, k := range current.MapKeys() {
r.every(current.MapIndex(k), path, v, f)
}
default:
panic("unsupported")
}
}
func (r *findResult[T]) Every(v reflect.Value, f func(reflect.Value, T)) {
for i := range r.Paths {
r.every(v, r.Paths[i].Path, r.Paths[i].Value, f)
}
}
func jsonName(field reflect.StructField) string {
name := strings.ToLower(field.Name)
if jsonName := field.Tag.Get("json"); jsonName != "" {
name = strings.Split(jsonName, ",")[0]
}
return name
}
func (r *findResult[T]) everyPB(current reflect.Value, path []int, pb *PathBuffer, v T, f func(reflect.Value, T)) {
switch reflect.Indirect(current).Kind() {
case reflect.Slice, reflect.Map:
// Ignore these. We only care about the leaf nodes.
default:
if len(path) == 0 {
f(current, v)
return
}
}
current = reflect.Indirect(current)
if current.Kind() == reflect.Invalid {
// Indirect may have resulted in no value, for example an optional field may
// have been omitted; just ignore it.
return
}
switch current.Kind() {
case reflect.Struct:
field := current.Type().Field(path[0])
pops := 0
if !field.Anonymous {
// The path name can come from one of four places: path parameter,
// query parameter, header parameter, or body field.
// TODO: pre-compute type/field names? Could save a few allocations.
pops++
if path := field.Tag.Get("path"); path != "" && pb.Len() == 0 {
pb.Push("path")
pb.Push(path)
pops++
} else if query := field.Tag.Get("query"); query != "" && pb.Len() == 0 {
pb.Push("query")
pb.Push(query)
pops++
} else if header := field.Tag.Get("header"); header != "" && pb.Len() == 0 {
pb.Push("header")
pb.Push(header)
pops++
} else {
// The body is _always_ in a field called "Body", which turns into
// `body` in the path buffer, so we don't need to push it separately
// like the params fields above.
pb.Push(jsonName(field))
}
}
r.everyPB(current.Field(path[0]), path[1:], pb, v, f)
for i := 0; i < pops; i++ {
pb.Pop()
}
case reflect.Slice:
for j := 0; j < current.Len(); j++ {
pb.PushIndex(j)
r.everyPB(current.Index(j), path, pb, v, f)
pb.Pop()
}
case reflect.Map:
for _, k := range current.MapKeys() {
if k.Kind() == reflect.String {
pb.Push(k.String())
} else {
pb.Push(fmt.Sprintf("%v", k.Interface()))
}
r.everyPB(current.MapIndex(k), path, pb, v, f)
pb.Pop()
}
default:
panic("unsupported")
}
}
func (r *findResult[T]) EveryPB(pb *PathBuffer, v reflect.Value, f func(reflect.Value, T)) {
for i := range r.Paths {
pb.Reset()
r.everyPB(v, r.Paths[i].Path, pb, r.Paths[i].Value, f)
}
}
func findInType[T comparable](t reflect.Type, onType func(reflect.Type, []int) T, onField func(reflect.StructField, []int) T, recurseFields bool, ignore ...string) *findResult[T] {
result := &findResult[T]{}
_findInType(t, []int{}, result, onType, onField, recurseFields, make(map[reflect.Type]struct{}), ignore...)
return result
}
func _findInType[T comparable](t reflect.Type, path []int, result *findResult[T], onType func(reflect.Type, []int) T, onField func(reflect.StructField, []int) T, recurseFields bool, visited map[reflect.Type]struct{}, ignore ...string) {
t = deref(t)
zero := reflect.Zero(reflect.TypeOf((*T)(nil)).Elem()).Interface()
ignoreAnonymous := false
if onType != nil {
if v := onType(t, path); v != zero {
result.Paths = append(result.Paths, findResultPath[T]{path, v})
// Found what we were looking for in the type, no need to go deeper.
// We do still want to potentially process each non-anonymous field,
// so only skip anonymous ones.
ignoreAnonymous = true
}
}
switch t.Kind() {
case reflect.Struct:
if _, ok := visited[t]; ok {
return
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
}
if slices.Contains(ignore, f.Name) {
continue
}
if ignoreAnonymous && f.Anonymous {
continue
}
fi := append([]int{}, path...)
fi = append(fi, i)
if onField != nil {
if v := onField(f, fi); v != zero {
result.Paths = append(result.Paths, findResultPath[T]{fi, v})
}
}
if f.Anonymous || recurseFields || deref(f.Type).Kind() != reflect.Struct {
// Always process embedded structs and named fields which are not
// structs. If `recurseFields` is true then we also process named
// struct fields recursively.
visited[t] = struct{}{}
_findInType(f.Type, fi, result, onType, onField, recurseFields, visited, ignore...)
delete(visited, t)
}
}
case reflect.Slice:
_findInType(t.Elem(), path, result, onType, onField, recurseFields, visited, ignore...)
case reflect.Map:
_findInType(t.Elem(), path, result, onType, onField, recurseFields, visited, ignore...)
}
}
func getHint(parent reflect.Type, name string, other string) string {
if parent.Name() != "" {
return parent.Name() + name
} else {
return other
}
}
type validateDeps struct {
pb *PathBuffer
res *ValidateResult
}
var validatePool = sync.Pool{
New: func() any {
return &validateDeps{
pb: &PathBuffer{buf: make([]byte, 0, 128)},
res: &ValidateResult{},
}
},
}
var bufPool = sync.Pool{
New: func() any {
return bytes.NewBuffer(make([]byte, 0, 128))
},
}
func writeResponse(api API, ctx Context, status int, ct string, body any) error {
if ct == "" {
// If no content type was provided, try to negotiate one with the client.
var err error
ct, err = api.Negotiate(ctx.Header("Accept"))
if err != nil {
notAccept := NewErrorWithContext(ctx, http.StatusNotAcceptable, "unable to marshal response", err)
if e := transformAndWrite(api, ctx, http.StatusNotAcceptable, "application/json", notAccept); e != nil {
return e
}
return err
}
if ctf, ok := body.(ContentTypeFilter); ok {
ct = ctf.ContentType(ct)
}
ctx.SetHeader("Content-Type", ct)
}
if err := transformAndWrite(api, ctx, status, ct, body); err != nil {
return err
}
return nil
}
func writeResponseWithPanic(api API, ctx Context, status int, ct string, body any) {
if err := writeResponse(api, ctx, status, ct, body); err != nil {
panic(err)
}
}
// transformAndWrite is a utility function to transform and write a response.
// It is best-effort as the status code and headers may have already been sent.
func transformAndWrite(api API, ctx Context, status int, ct string, body any) error {
// Try to transform and then marshal/write the response.
// Status code was already sent, so just log the error if something fails,
// and do our best to stuff it into the body of the response.
tval, terr := api.Transform(ctx, strconv.Itoa(status), body)
if terr != nil {
ctx.BodyWriter().Write([]byte("error transforming response"))
// When including tval in the panic message, the server may become unresponsive for some time if the value is very large
// therefore, it has been removed from the panic message
return fmt.Errorf("error transforming response for %s %s %d: %w", ctx.Operation().Method, ctx.Operation().Path, status, terr)
}
ctx.SetStatus(status)
if status != http.StatusNoContent && status != http.StatusNotModified {
if merr := api.Marshal(ctx.BodyWriter(), ct, tval); merr != nil {
if errors.Is(ctx.Context().Err(), context.Canceled) {
// The client disconnected, so don't bother writing anything. Attempt
// to set the status in case it'll get logged. Technically this was
// not a normal successful request.
ctx.SetStatus(499)
return nil
}
ctx.BodyWriter().Write([]byte("error marshaling response"))
// When including tval in the panic message, the server may become unresponsive for some time if the value is very large
// therefore, it has been removed from the panic message
return fmt.Errorf("error marshaling response for %s %s %d: %w", ctx.Operation().Method, ctx.Operation().Path, status, merr)
}
}
return nil
}
func parseArrElement[T any](values []string, parse func(string) (T, error)) ([]T, error) {
result := make([]T, 0, len(values))
for i := 0; i < len(values); i++ {
v, err := parse(values[i])
if err != nil {
return nil, err
}
result = append(result, v)
}
return result, nil
}
// writeHeader is a utility function to write a header value to the response.
// the `write` function should be either `ctx.SetHeader` or `ctx.AppendHeader`.
func writeHeader(write func(string, string), info *headerInfo, f reflect.Value) {
switch f.Kind() {
case reflect.String:
if f.String() == "" {
// Don't set empty headers.
return
}
write(info.Name, f.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
write(info.Name, strconv.FormatInt(f.Int(), 10))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
write(info.Name, strconv.FormatUint(f.Uint(), 10))
case reflect.Float32, reflect.Float64:
write(info.Name, strconv.FormatFloat(f.Float(), 'f', -1, 64))
case reflect.Bool:
write(info.Name, strconv.FormatBool(f.Bool()))
default:
if f.Type() == timeType && !f.Interface().(time.Time).IsZero() {
write(info.Name, f.Interface().(time.Time).Format(info.TimeFormat))
return
}
// If the field value has a `String() string` method, use it.
if f.CanAddr() {
if s, ok := f.Addr().Interface().(fmt.Stringer); ok {
write(info.Name, s.String())
return
}
}
write(info.Name, fmt.Sprintf("%v", f.Interface()))
}
}
// Register an operation handler for an API. The handler must be a function that
// takes a context and a pointer to the input struct and returns a pointer to the
// output struct and an error. The input struct must be a struct with fields
// for the request path/query/header/cookie parameters and/or body. The output
// struct must be a struct with fields for the output headers and body of the
// operation, if any.
//
// huma.Register(api, huma.Operation{
// OperationID: "get-greeting",
// Method: http.MethodGet,
// Path: "/greeting/{name}",
// Summary: "Get a greeting",
// }, func(ctx context.Context, input *GreetingInput) (*GreetingOutput, error) {
// if input.Name == "bob" {
// return nil, huma.Error404NotFound("no greeting for bob")
// }
// resp := &GreetingOutput{}
// resp.MyHeader = "MyValue"
// resp.Body.Message = fmt.Sprintf("Hello, %s!", input.Name)
// return resp, nil
// })
func Register[I, O any](api API, op Operation, handler func(context.Context, *I) (*O, error)) {
oapi := api.OpenAPI()
registry := oapi.Components.Schemas
if op.Method == "" || op.Path == "" {
panic("method and path must be specified in operation")
}
inputType := reflect.TypeOf((*I)(nil)).Elem()
if inputType.Kind() != reflect.Struct {
panic("input must be a struct")
}
inputParams := findParams(registry, &op, inputType)
inputBodyIndex := []int{}
hasInputBody := false
if f, ok := inputType.FieldByName("Body"); ok {
hasInputBody = true
inputBodyIndex = f.Index
if op.RequestBody == nil {
op.RequestBody = &RequestBody{}
}
required := f.Type.Kind() != reflect.Ptr && f.Type.Kind() != reflect.Interface
if f.Tag.Get("required") == "true" {
required = true
}
contentType := "application/json"
if c := f.Tag.Get("contentType"); c != "" {
contentType = c
}
hint := getHint(inputType, f.Name, op.OperationID+"Request")
if nameHint := f.Tag.Get("nameHint"); nameHint != "" {
hint = nameHint
}
s := SchemaFromField(registry, f, hint)
op.RequestBody.Required = required
if op.RequestBody.Content == nil {
op.RequestBody.Content = map[string]*MediaType{}
}
op.RequestBody.Content[contentType] = &MediaType{Schema: s}
if op.BodyReadTimeout == 0 {
// 5 second default
op.BodyReadTimeout = 5 * time.Second
}
if op.MaxBodyBytes == 0 {
// 1 MB default
op.MaxBodyBytes = 1024 * 1024
}
}
rawBodyIndex := []int{}
rawBodyMultipart := false
rawBodyDecodedMultipart := false
if f, ok := inputType.FieldByName("RawBody"); ok {
rawBodyIndex = f.Index
if op.RequestBody == nil {
op.RequestBody = &RequestBody{
Required: true,
}
}
if op.RequestBody.Content == nil {
op.RequestBody.Content = map[string]*MediaType{}
}
contentType := "application/octet-stream"
if f.Type.String() == "multipart.Form" {
contentType = "multipart/form-data"
rawBodyMultipart = true
}
if strings.HasPrefix(f.Type.Name(), "MultipartFormFiles") {
contentType = "multipart/form-data"
rawBodyDecodedMultipart = true
}
if c := f.Tag.Get("contentType"); c != "" {
contentType = c
}
switch contentType {
case "multipart/form-data":
if op.RequestBody.Content["multipart/form-data"] != nil {
break
}
if rawBodyMultipart {
op.RequestBody.Content["multipart/form-data"] = &MediaType{
Schema: &Schema{
Type: "object",
Properties: map[string]*Schema{
"name": {
Type: "string",
Description: "general purpose name for multipart form value",
},
"filename": {
Type: "string",
Format: "binary",
Description: "filename of the file being uploaded",
},
},
},
}
}
if rawBodyDecodedMultipart {
dataField, ok := f.Type.FieldByName("data")
if !ok {
panic("Expected type MultipartFormFiles[T] to have a 'data *T' generic pointer field")
}
op.RequestBody.Content["multipart/form-data"] = &MediaType{
Schema: multiPartFormFileSchema(dataField.Type.Elem()),
Encoding: multiPartContentEncoding(dataField.Type.Elem()),
}
op.RequestBody.Required = false
}
default:
op.RequestBody.Content[contentType] = &MediaType{
Schema: &Schema{
Type: "string",
Format: "binary",
},
}
}
}
if op.RequestBody != nil {
for _, mediatype := range op.RequestBody.Content {
if mediatype.Schema != nil {
// Ensure all schema validation errors are set up properly as some
// parts of the schema may have been user-supplied.
mediatype.Schema.PrecomputeMessages()
}
}
}
var inSchema *Schema
if op.RequestBody != nil && op.RequestBody.Content != nil && op.RequestBody.Content["application/json"] != nil && op.RequestBody.Content["application/json"].Schema != nil {
hasInputBody = true
inSchema = op.RequestBody.Content["application/json"].Schema
}
resolvers := findResolvers(resolverType, inputType)
defaults := findDefaults(registry, inputType)
if op.Responses == nil {
op.Responses = map[string]*Response{}
}
outputType := reflect.TypeOf((*O)(nil)).Elem()
if outputType.Kind() != reflect.Struct {
panic("output must be a struct")
}
outStatusIndex := -1
if f, ok := outputType.FieldByName("Status"); ok {
outStatusIndex = f.Index[0]
if f.Type.Kind() != reflect.Int {
panic("status field must be an int")
}
// TODO: enum tag?
// TODO: register each of the possible responses with the right model
// and headers down below.
}
outHeaders := findHeaders(outputType)
outBodyIndex := -1
outBodyFunc := false
if f, ok := outputType.FieldByName("Body"); ok {
outBodyIndex = f.Index[0]
if f.Type.Kind() == reflect.Func {
outBodyFunc = true
if f.Type != bodyCallbackType {
panic("body field must be a function with signature func(huma.Context)")
}
}
status := op.DefaultStatus
if status == 0 {
status = http.StatusOK
}
statusStr := strconv.Itoa(status)
if op.Responses[statusStr] == nil {
op.Responses[statusStr] = &Response{}
}
if op.Responses[statusStr].Description == "" {
op.Responses[statusStr].Description = http.StatusText(status)
}
if op.Responses[statusStr].Headers == nil {
op.Responses[statusStr].Headers = map[string]*Param{}
}
if !outBodyFunc {
hint := getHint(outputType, f.Name, op.OperationID+"Response")
if nameHint := f.Tag.Get("nameHint"); nameHint != "" {
hint = nameHint
}
outSchema := SchemaFromField(registry, f, hint)
if op.Responses[statusStr].Content == nil {
op.Responses[statusStr].Content = map[string]*MediaType{}
}
// Check if the field's type implements ContentTypeFilter
contentType := "application/json"
if reflect.PointerTo(f.Type).Implements(reflect.TypeFor[ContentTypeFilter]()) {
instance := reflect.New(f.Type).Interface().(ContentTypeFilter)
contentType = instance.ContentType(contentType)
}
if len(op.Responses[statusStr].Content) == 0 {
op.Responses[statusStr].Content[contentType] = &MediaType{}
}
if op.Responses[statusStr].Content[contentType] != nil && op.Responses[statusStr].Content[contentType].Schema == nil {
op.Responses[statusStr].Content[contentType].Schema = outSchema
}
}
}
if op.DefaultStatus == 0 {
if outBodyIndex != -1 {
op.DefaultStatus = http.StatusOK
} else {
op.DefaultStatus = http.StatusNoContent
}
}
defaultStatusStr := strconv.Itoa(op.DefaultStatus)
if op.Responses[defaultStatusStr] == nil {
op.Responses[defaultStatusStr] = &Response{
Description: http.StatusText(op.DefaultStatus),
}
}
for _, entry := range outHeaders.Paths {
// Document the header's name and type.
if op.Responses[defaultStatusStr].Headers == nil {
op.Responses[defaultStatusStr].Headers = map[string]*Param{}
}
v := entry.Value
f := v.Field
if f.Type.Kind() == reflect.Slice {
f.Type = deref(f.Type.Elem())
}
if reflect.PointerTo(f.Type).Implements(fmtStringerType) {
// Special case: this field will be written as a string by calling
// `.String()` on the value.
f.Type = stringType
}
op.Responses[defaultStatusStr].Headers[v.Name] = &Header{
// We need to generate the schema from the field to get validation info
// like min/max and enums. Useful to let the client know possible values.
Schema: SchemaFromField(registry, f, getHint(outputType, f.Name, op.OperationID+defaultStatusStr+v.Name)),
}
}
if len(op.Errors) > 0 && (len(inputParams.Paths) > 0 || hasInputBody) {
op.Errors = append(op.Errors, http.StatusUnprocessableEntity)
}
if len(op.Errors) > 0 {
op.Errors = append(op.Errors, http.StatusInternalServerError)
}
exampleErr := NewError(0, "")
errContentType := "application/json"
if ctf, ok := exampleErr.(ContentTypeFilter); ok {
errContentType = ctf.ContentType(errContentType)
}
errType := deref(reflect.TypeOf(exampleErr))
errSchema := registry.Schema(errType, true, getHint(errType, "", "Error"))
for _, code := range op.Errors {
op.Responses[strconv.Itoa(code)] = &Response{
Description: http.StatusText(code),
Content: map[string]*MediaType{
errContentType: {
Schema: errSchema,
},
},
}
}
if len(op.Responses) <= 1 && len(op.Errors) == 0 {
// No errors are defined, so set a default response.
op.Responses["default"] = &Response{
Description: "Error",
Content: map[string]*MediaType{
errContentType: {
Schema: errSchema,
},
},
}
}
if !op.Hidden {
oapi.AddOperation(&op)
}
a := api.Adapter()
a.Handle(&op, api.Middlewares().Handler(op.Middlewares.Handler(func(ctx Context) {
var input I
// Get the validation dependencies from the shared pool.
deps := validatePool.Get().(*validateDeps)
defer func() {
deps.pb.Reset()
deps.res.Reset()
validatePool.Put(deps)
}()
pb := deps.pb
res := deps.res
errStatus := http.StatusUnprocessableEntity
var cookies map[string]*http.Cookie
v := reflect.ValueOf(&input).Elem()
inputParams.Every(v, func(f reflect.Value, p *paramFieldInfo) {
f = reflect.Indirect(f)
if f.Kind() == reflect.Invalid {
return
}
var value string
switch p.Loc {
case "path":
value = ctx.Param(p.Name)
case "query":
value = ctx.Query(p.Name)
case "header":
value = ctx.Header(p.Name)
case "cookie":
if cookies == nil {
// Only parse the cookie headers once, on-demand.
cookies = map[string]*http.Cookie{}
for _, c := range ReadCookies(ctx) {
cookies[c.Name] = c
}
}
if c, ok := cookies[p.Name]; ok {
// Special case: http.Cookie type, meaning we want the entire parsed
// cookie struct, not just the value.
if f.Type() == cookieType {
f.Set(reflect.ValueOf(cookies[p.Name]).Elem())
return
}
value = c.Value
}
}
pb.Reset()
pb.Push(p.Loc)
pb.Push(p.Name)
if value == "" && p.Default != "" {
value = p.Default
}
if !op.SkipValidateParams && p.Required && value == "" {
// Path params are always required.
res.Add(pb, "", "required "+p.Loc+" parameter is missing")
return
}
if value != "" {
var pv any
switch p.Type.Kind() {
case reflect.String:
f.SetString(value)
pv = value
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v, err := strconv.ParseInt(value, 10, 64)
if err != nil {
res.Add(pb, value, "invalid integer")
return
}
f.SetInt(v)
pv = v
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v, err := strconv.ParseUint(value, 10, 64)
if err != nil {
res.Add(pb, value, "invalid integer")
return
}
f.SetUint(v)
pv = v
case reflect.Float32, reflect.Float64:
v, err := strconv.ParseFloat(value, 64)
if err != nil {
res.Add(pb, value, "invalid float")
return
}
f.SetFloat(v)
pv = v
case reflect.Bool:
v, err := strconv.ParseBool(value)
if err != nil {
res.Add(pb, value, "invalid boolean")
return
}
f.SetBool(v)