-
-
Notifications
You must be signed in to change notification settings - Fork 560
/
server.go
1435 lines (1351 loc) Β· 48.2 KB
/
server.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 codegen
import (
"fmt"
"path/filepath"
"reflect"
"strings"
"goa.design/goa/v3/codegen"
"goa.design/goa/v3/codegen/service"
"goa.design/goa/v3/expr"
)
// ServerFiles returns the generated HTTP server files.
func ServerFiles(genpkg string, root *expr.RootExpr) []*codegen.File {
var files []*codegen.File
for _, svc := range root.API.HTTP.Services {
files = append(files, serverFile(genpkg, svc))
if f := websocketServerFile(genpkg, svc); f != nil {
files = append(files, f)
}
}
for _, svc := range root.API.HTTP.Services {
if f := serverEncodeDecodeFile(genpkg, svc); f != nil {
files = append(files, f)
}
}
return files
}
// server returns the file implementing the HTTP server.
func serverFile(genpkg string, svc *expr.HTTPServiceExpr) *codegen.File {
data := HTTPServices.Get(svc.Name())
svcName := data.Service.PathName
path := filepath.Join(codegen.Gendir, "http", svcName, "server", "server.go")
title := fmt.Sprintf("%s HTTP server", svc.Name())
funcs := map[string]interface{}{
"join": func(ss []string, s string) string { return strings.Join(ss, s) },
"hasWebSocket": hasWebSocket,
"isWebSocketEndpoint": isWebSocketEndpoint,
"viewedServerBody": viewedServerBody,
"mustDecodeRequest": mustDecodeRequest,
"addLeadingSlash": addLeadingSlash,
"removeTrailingIndexHTML": removeTrailingIndexHTML,
}
sections := []*codegen.SectionTemplate{
codegen.Header(title, "server", []*codegen.ImportSpec{
{Path: "context"},
{Path: "fmt"},
{Path: "io"},
{Path: "mime/multipart"},
{Path: "net/http"},
{Path: "path"},
{Path: "strings"},
{Path: "github.com/gorilla/websocket"},
codegen.GoaImport(""),
codegen.GoaNamedImport("http", "goahttp"),
{Path: genpkg + "/" + svcName, Name: data.Service.PkgName},
{Path: genpkg + "/" + svcName + "/" + "views", Name: data.Service.ViewsPkg},
}),
}
sections = append(sections, &codegen.SectionTemplate{Name: "server-struct", Source: serverStructT, Data: data})
sections = append(sections, &codegen.SectionTemplate{Name: "server-mountpoint", Source: mountPointStructT, Data: data})
for _, e := range data.Endpoints {
if e.MultipartRequestDecoder != nil {
sections = append(sections, &codegen.SectionTemplate{
Name: "multipart-request-decoder-type",
Source: multipartRequestDecoderTypeT,
Data: e.MultipartRequestDecoder,
})
}
}
sections = append(sections, &codegen.SectionTemplate{Name: "server-init", Source: serverInitT, Data: data, FuncMap: funcs})
sections = append(sections, &codegen.SectionTemplate{Name: "server-service", Source: serverServiceT, Data: data})
sections = append(sections, &codegen.SectionTemplate{Name: "server-use", Source: serverUseT, Data: data})
sections = append(sections, &codegen.SectionTemplate{Name: "server-mount", Source: serverMountT, Data: data, FuncMap: funcs})
for _, e := range data.Endpoints {
sections = append(sections, &codegen.SectionTemplate{Name: "server-handler", Source: serverHandlerT, Data: e})
sections = append(sections, &codegen.SectionTemplate{Name: "server-handler-init", Source: serverHandlerInitT, FuncMap: funcs, Data: e})
}
for _, s := range data.FileServers {
sections = append(sections, &codegen.SectionTemplate{Name: "server-files", Source: fileServerT, FuncMap: funcs, Data: s})
}
return &codegen.File{Path: path, SectionTemplates: sections}
}
// serverEncodeDecodeFile returns the file defining the HTTP server encoding and
// decoding logic.
func serverEncodeDecodeFile(genpkg string, svc *expr.HTTPServiceExpr) *codegen.File {
data := HTTPServices.Get(svc.Name())
svcName := data.Service.PathName
path := filepath.Join(codegen.Gendir, "http", svcName, "server", "encode_decode.go")
title := fmt.Sprintf("%s HTTP server encoders and decoders", svc.Name())
imports := []*codegen.ImportSpec{
{Path: "context"},
{Path: "errors"},
{Path: "fmt"},
{Path: "io"},
{Path: "net/http"},
{Path: "strconv"},
{Path: "strings"},
{Path: "encoding/json"},
{Path: "mime/multipart"},
{Path: "unicode/utf8"},
codegen.GoaImport(""),
codegen.GoaNamedImport("http", "goahttp"),
{Path: genpkg + "/" + svcName, Name: data.Service.PkgName},
{Path: genpkg + "/" + svcName + "/" + "views", Name: data.Service.ViewsPkg},
}
imports = append(imports, data.Service.UserTypeImports...)
sections := []*codegen.SectionTemplate{codegen.Header(title, "server", imports)}
for _, e := range data.Endpoints {
if e.Redirect == nil && !isWebSocketEndpoint(e) {
sections = append(sections, &codegen.SectionTemplate{
Name: "response-encoder",
FuncMap: transTmplFuncs(svc),
Source: responseEncoderT,
Data: e,
})
}
if mustDecodeRequest(e) {
fm := transTmplFuncs(svc)
fm["mapQueryDecodeData"] = mapQueryDecodeData
sections = append(sections, &codegen.SectionTemplate{
Name: "request-decoder",
Source: requestDecoderT,
FuncMap: fm,
Data: e,
})
}
if e.MultipartRequestDecoder != nil {
fm := transTmplFuncs(svc)
fm["mapQueryDecodeData"] = mapQueryDecodeData
sections = append(sections, &codegen.SectionTemplate{
Name: "multipart-request-decoder",
Source: multipartRequestDecoderT,
FuncMap: fm,
Data: e.MultipartRequestDecoder,
})
}
if len(e.Errors) > 0 {
sections = append(sections, &codegen.SectionTemplate{
Name: "error-encoder",
Source: errorEncoderT,
FuncMap: transTmplFuncs(svc),
Data: e,
})
}
}
for _, h := range data.ServerTransformHelpers {
sections = append(sections, &codegen.SectionTemplate{
Name: "server-transform-helper",
Source: transformHelperT,
Data: h,
})
}
// If all endpoints use skip encoding and decoding of both payloads and
// results and define no error then this file is irrelevant.
if len(sections) == 1 {
return nil
}
return &codegen.File{Path: path, SectionTemplates: sections}
}
func transTmplFuncs(s *expr.HTTPServiceExpr) map[string]interface{} {
return map[string]interface{}{
"goTypeRef": func(dt expr.DataType) string {
return service.Services.Get(s.Name()).Scope.GoTypeRef(&expr.AttributeExpr{Type: dt})
},
"isAliased": func(dt expr.DataType) bool {
_, ok := dt.(expr.UserType)
return ok
},
"conversionData": conversionData,
"headerConversionData": headerConversionData,
"printValue": printValue,
"viewedServerBody": viewedServerBody,
}
}
// mustDecodeRequest returns true if the Payload type is not empty.
func mustDecodeRequest(e *EndpointData) bool {
return e.Payload.Ref != ""
}
// conversionData creates a template context suitable for executing the
// "type_conversion" template.
func conversionData(varName, name string, dt expr.DataType) map[string]interface{} {
return map[string]interface{}{
"VarName": varName,
"Name": name,
"Type": dt,
}
}
// headerConversionData produces the template data suitable for executing the
// "header_conversion" template.
func headerConversionData(dt expr.DataType, varName string, required bool, target string) map[string]interface{} {
return map[string]interface{}{
"Type": dt,
"VarName": varName,
"Required": required,
"Target": target,
}
}
// printValue generates the Go code for a literal string containing the given
// value. printValue panics if the data type is not a primitive or an array.
func printValue(dt expr.DataType, v interface{}) string {
switch actual := dt.(type) {
case *expr.Array:
val := reflect.ValueOf(v)
elems := make([]string, val.Len())
for i := 0; i < val.Len(); i++ {
elems[i] = printValue(actual.ElemType.Type, val.Index(i).Interface())
}
return strings.Join(elems, ", ")
case expr.Primitive:
return fmt.Sprintf("%v", v)
default:
panic("unsupported type value " + dt.Name()) // bug
}
}
// viewedServerBody returns the type data that uses the given view for
// rendering.
func viewedServerBody(sbd []*TypeData, view string) *TypeData {
for _, v := range sbd {
if v.View == view {
return v
}
}
panic("view not found in server body types: " + view)
}
func addLeadingSlash(s string) string {
if strings.HasPrefix(s, "/") {
return s
}
return "/" + s
}
func removeTrailingIndexHTML(s string) string {
if strings.HasSuffix(s, "/index.html") {
return strings.TrimSuffix(s, "index.html")
}
return s
}
func mapQueryDecodeData(dt expr.DataType, varName string, inc int) map[string]interface{} {
return map[string]interface{}{
"Type": dt,
"VarName": varName,
"Loop": string(rune(97 + inc)),
"Increment": inc + 1,
"Depth": codegen.MapDepth(expr.AsMap(dt)),
}
}
// input: ServiceData
const serverStructT = `{{ printf "%s lists the %s service endpoint HTTP handlers." .ServerStruct .Service.Name | comment }}
type {{ .ServerStruct }} struct {
Mounts []*{{ .MountPointStruct }}
{{- range .Endpoints }}
{{ .Method.VarName }} http.Handler
{{- end }}
{{- range .FileServers }}
{{ .VarName }} http.Handler
{{- end }}
}
// ErrorNamer is an interface implemented by generated error structs that
// exposes the name of the error as defined in the design.
type ErrorNamer interface {
ErrorName() string
}
`
// input: ServiceData
const mountPointStructT = `{{ printf "%s holds information about the mounted endpoints." .MountPointStruct | comment }}
type {{ .MountPointStruct }} struct {
{{ printf "Method is the name of the service method served by the mounted HTTP handler." | comment }}
Method string
{{ printf "Verb is the HTTP method used to match requests to the mounted handler." | comment }}
Verb string
{{ printf "Pattern is the HTTP request path pattern used to match requests to the mounted handler." | comment }}
Pattern string
}
`
// input: ServiceData
const serverInitT = `{{ printf "%s instantiates HTTP handlers for all the %s service endpoints using the provided encoder and decoder. The handlers are mounted on the given mux using the HTTP verb and path defined in the design. errhandler is called whenever a response fails to be encoded. formatter is used to format errors returned by the service methods prior to encoding. Both errhandler and formatter are optional and can be nil." .ServerInit .Service.Name | comment }}
func {{ .ServerInit }}(
e *{{ .Service.PkgName }}.Endpoints,
mux goahttp.Muxer,
decoder func(*http.Request) goahttp.Decoder,
encoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
errhandler func(context.Context, http.ResponseWriter, error),
formatter func(err error) goahttp.Statuser,
{{- if hasWebSocket . }}
upgrader goahttp.Upgrader,
configurer *ConnConfigurer,
{{- end }}
{{- range .Endpoints }}
{{- if .MultipartRequestDecoder }}
{{ .MultipartRequestDecoder.VarName }} {{ .MultipartRequestDecoder.FuncName }},
{{- end }}
{{- end }}
{{- range .FileServers }}
{{ .ArgName }} http.FileSystem,
{{- end }}
) *{{ .ServerStruct }} {
{{- if hasWebSocket . }}
if configurer == nil {
configurer = &ConnConfigurer{}
}
{{- end }}
{{- range .FileServers }}
if {{ .ArgName }} == nil {
{{ .ArgName }} = http.Dir(".")
}
{{- end }}
return &{{ .ServerStruct }}{
Mounts: []*{{ .MountPointStruct }}{
{{- range $e := .Endpoints }}
{{- range $e.Routes }}
{"{{ $e.Method.VarName }}", "{{ .Verb }}", "{{ .Path }}"},
{{- end }}
{{- end }}
{{- range .FileServers }}
{{- $filepath := .FilePath }}
{{- range .RequestPaths }}
{"{{ $filepath }}", "GET", "{{ . }}"},
{{- end }}
{{- end }}
},
{{- range .Endpoints }}
{{ .Method.VarName }}: {{ .HandlerInit }}(e.{{ .Method.VarName }}, mux, {{ if .MultipartRequestDecoder }}{{ .MultipartRequestDecoder.InitName }}(mux, {{ .MultipartRequestDecoder.VarName }}){{ else }}decoder{{ end }}, encoder, errhandler, formatter{{ if isWebSocketEndpoint . }}, upgrader, configurer.{{ .Method.VarName }}Fn{{ end }}),
{{- end }}
{{- range .FileServers }}
{{ .VarName }}: http.FileServer({{ .ArgName }}),
{{- end }}
}
}
`
// input: ServiceData
const serverServiceT = `{{ printf "%s returns the name of the service served." .ServerService | comment }}
func (s *{{ .ServerStruct }}) {{ .ServerService }}() string { return "{{ .Service.Name }}" }
`
// input: ServiceData
const serverUseT = `{{ printf "Use wraps the server handlers with the given middleware." | comment }}
func (s *{{ .ServerStruct }}) Use(m func(http.Handler) http.Handler) {
{{- range .Endpoints }}
s.{{ .Method.VarName }} = m(s.{{ .Method.VarName }})
{{- end }}
}
`
// input: ServiceData
const serverMountT = `{{ printf "%s configures the mux to serve the %s endpoints." .MountServer .Service.Name | comment }}
func {{ .MountServer }}(mux goahttp.Muxer, h *{{ .ServerStruct }}) {
{{- range .Endpoints }}
{{ .MountHandler }}(mux, h.{{ .Method.VarName }})
{{- end }}
{{- range .FileServers }}
{{- if .Redirect }}
{{ .MountHandler }}(mux, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "{{ .Redirect.URL }}", {{ .Redirect.StatusCode }})
}))
{{- else if .IsDir }}
{{- $filepath := addLeadingSlash (removeTrailingIndexHTML .FilePath) }}
{{ .MountHandler }}(mux, {{ range .RequestPaths }}{{if ne . $filepath }}goahttp.Replace("{{ . }}", "{{ $filepath }}", {{ end }}{{ end }}h.{{ .VarName }}){{ range .RequestPaths }}{{ if ne . $filepath }}){{ end}}{{ end }}
{{- else }}
{{- $filepath := addLeadingSlash (removeTrailingIndexHTML .FilePath) }}
{{ .MountHandler }}(mux, {{ range .RequestPaths }}{{if ne . $filepath }}goahttp.Replace("", "{{ $filepath }}", {{ end }}{{ end }}h.{{ .VarName }}){{ range .RequestPaths }}{{ if ne . $filepath }}){{ end}}{{ end }}
{{- end }}
{{- end }}
}
{{ printf "%s configures the mux to serve the %s endpoints." .MountServer .Service.Name | comment }}
func (s *{{ .ServerStruct }}) {{ .MountServer }}(mux goahttp.Muxer) {
{{ .MountServer }}(mux, s)
}
`
// input: EndpointData
const serverHandlerT = `{{ printf "%s configures the mux to serve the %q service %q endpoint." .MountHandler .ServiceName .Method.Name | comment }}
func {{ .MountHandler }}(mux goahttp.Muxer, h http.Handler) {
f, ok := h.(http.HandlerFunc)
if !ok {
f = func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
}
{{- range .Routes }}
mux.Handle("{{ .Verb }}", "{{ .Path }}", f)
{{- end }}
}
`
// input: FileServerData
const fileServerT = `{{ printf "%s configures the mux to serve GET request made to %q." .MountHandler (join .RequestPaths ", ") | comment }}
func {{ .MountHandler }}(mux goahttp.Muxer, h http.Handler) {
{{- if .IsDir }}
{{- range .RequestPaths }}
mux.Handle("GET", "{{ . }}{{if ne . "/"}}/{{end}}", h.ServeHTTP)
mux.Handle("GET", "{{ . }}{{if ne . "/"}}/{{end}}*{{ $.PathParam }}", h.ServeHTTP)
{{- end }}
{{- else }}
{{- range .RequestPaths }}
mux.Handle("GET", "{{ . }}", h.ServeHTTP)
{{- end }}
{{- end }}
}
`
// input: EndpointData
const serverHandlerInitT = `{{ printf "%s creates a HTTP handler which loads the HTTP request and calls the %q service %q endpoint." .HandlerInit .ServiceName .Method.Name | comment }}
func {{ .HandlerInit }}(
endpoint goa.Endpoint,
mux goahttp.Muxer,
decoder func(*http.Request) goahttp.Decoder,
encoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
errhandler func(context.Context, http.ResponseWriter, error),
formatter func(err error) goahttp.Statuser,
{{- if isWebSocketEndpoint . }}
upgrader goahttp.Upgrader,
configurer goahttp.ConnConfigureFunc,
{{- end }}
) http.Handler {
{{- if (or (mustDecodeRequest .) (not (or .Redirect (isWebSocketEndpoint .))) (not .Redirect) .Method.SkipResponseBodyEncodeDecode) }}
var (
{{- end }}
{{- if mustDecodeRequest . }}
decodeRequest = {{ .RequestDecoder }}(mux, decoder)
{{- end }}
{{- if not (or .Redirect (isWebSocketEndpoint .)) }}
encodeResponse = {{ .ResponseEncoder }}(encoder)
{{- end }}
{{- if (or (mustDecodeRequest .) (not .Redirect) .Method.SkipResponseBodyEncodeDecode) }}
encodeError = {{ if .Errors }}{{ .ErrorEncoder }}{{ else }}goahttp.ErrorEncoder{{ end }}(encoder, formatter)
{{- end }}
{{- if (or (mustDecodeRequest .) (not (or .Redirect (isWebSocketEndpoint .))) (not .Redirect) .Method.SkipResponseBodyEncodeDecode) }}
)
{{- end }}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), goahttp.AcceptTypeKey, r.Header.Get("Accept"))
ctx = context.WithValue(ctx, goa.MethodKey, {{ printf "%q" .Method.Name }})
ctx = context.WithValue(ctx, goa.ServiceKey, {{ printf "%q" .ServiceName }})
{{- if mustDecodeRequest . }}
{{ if .Redirect }}_{{ else }}payload{{ end }}, err := decodeRequest(r)
if err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
{{- else if not .Redirect }}
var err error
{{- end }}
{{- if isWebSocketEndpoint . }}
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
v := &{{ .ServicePkgName }}.{{ .Method.ServerStream.EndpointStruct }}{
Stream: &{{ .ServerWebSocket.VarName }}{
upgrader: upgrader,
configurer: configurer,
cancel: cancel,
w: w,
r: r,
},
{{- if .Payload.Ref }}
Payload: payload.({{ .Payload.Ref }}),
{{- end }}
}
_, err = endpoint(ctx, v)
{{- else if .Method.SkipRequestBodyEncodeDecode }}
data := &{{ .ServicePkgName }}.{{ .Method.RequestStruct }}{ {{ if .Payload.Ref }}Payload: payload.({{ .Payload.Ref }}), {{ end }}Body: r.Body }
res, err := endpoint(ctx, data)
{{- else if .Redirect }}
http.Redirect(w, r, "{{ .Redirect.URL }}", {{ .Redirect.StatusCode }})
{{- else }}
res, err := endpoint(ctx, {{ if .Payload.Ref }}payload{{ else }}nil{{ end }})
{{- end }}
{{- if not .Redirect }}
if err != nil {
{{- if isWebSocketEndpoint . }}
if _, werr := w.Write(nil); werr == http.ErrHijacked {
// Response writer has been hijacked, do not encode the error
errhandler(ctx, w, err)
return
}
{{- end }}
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
{{- end }}
{{- if .Method.SkipResponseBodyEncodeDecode }}
o := res.(*{{ .ServicePkgName }}.{{ .Method.ResponseStruct }})
defer o.Body.Close()
{{- end }}
{{- if not (or .Redirect (isWebSocketEndpoint .)) }}
if err := encodeResponse(ctx, w, {{ if and .Method.SkipResponseBodyEncodeDecode .Result.Ref }}o.Result{{ else }}res{{ end }}); err != nil {
errhandler(ctx, w, err)
{{- if .Method.SkipResponseBodyEncodeDecode }}
return
{{- end }}
}
{{- end }}
{{- if .Method.SkipResponseBodyEncodeDecode }}
if _, err := io.Copy(w, o.Body); err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
}
{{- end }}
})
}
`
// input: TransformFunctionData
const transformHelperT = `{{ printf "%s builds a value of type %s from a value of type %s." .Name .ResultTypeRef .ParamTypeRef | comment }}
func {{ .Name }}(v {{ .ParamTypeRef }}) {{ .ResultTypeRef }} {
{{ .Code }}
return res
}
`
// input: EndpointData
const requestDecoderT = `{{ printf "%s returns a decoder for requests sent to the %s %s endpoint." .RequestDecoder .ServiceName .Method.Name | comment }}
func {{ .RequestDecoder }}(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {
return func(r *http.Request) (interface{}, error) {
{{- if .MultipartRequestDecoder }}
var payload {{ .Payload.Ref }}
if err := decoder(r).Decode(&payload); err != nil {
return nil, goa.DecodePayloadError(err.Error())
}
{{- else if .Payload.Request.ServerBody }}
var (
body {{ .Payload.Request.ServerBody.VarName }}
err error
)
err = decoder(r).Decode(&body)
if err != nil {
{{- if .Payload.Request.MustHaveBody }}
if err == io.EOF {
return nil, goa.MissingPayloadError()
}
{{- else }}
if err == io.EOF {
err = nil
} else {
{{- end }}
return nil, goa.DecodePayloadError(err.Error())
{{- if not .Payload.Request.MustHaveBody }}
}
{{- end }}
}
{{- if .Payload.Request.ServerBody.ValidateRef }}
{{ .Payload.Request.ServerBody.ValidateRef }}
if err != nil {
return nil, err
}
{{- end }}
{{- end }}
{{- if not .MultipartRequestDecoder }}
{{- template "request_elements" .Payload.Request }}
{{- if .Payload.Request.MustValidate }}
if err != nil {
return nil, err
}
{{- end }}
{{- if .Payload.Request.PayloadInit }}
payload := {{ .Payload.Request.PayloadInit.Name }}({{ range .Payload.Request.PayloadInit.ServerArgs }}{{ .Ref }}, {{ end }})
{{- else if .Payload.DecoderReturnValue }}
payload := {{ .Payload.DecoderReturnValue }}
{{- else }}
payload := body
{{- end }}
{{- end }}
{{- if .BasicScheme }}{{ with .BasicScheme }}
user, pass, {{ if or .UsernameRequired .PasswordRequired }}ok{{ else }}_{{ end }} := r.BasicAuth()
{{- if or .UsernameRequired .PasswordRequired}}
if !ok {
return nil, goa.MissingFieldError("Authorization", "header")
}
{{- end }}
payload.{{ .UsernameField }} = {{ if .UsernamePointer }}&{{ end }}user
payload.{{ .PasswordField }} = {{ if .PasswordPointer }}&{{ end }}pass
{{- end }}{{ end }}
{{- range .HeaderSchemes }}
{{- if not .CredRequired }}
if payload.{{ .CredField }} != nil {
{{- end }}
if strings.Contains({{ if .CredPointer }}*{{ end }}payload.{{ .CredField }}, " ") {
// Remove authorization scheme prefix (e.g. "Bearer")
cred := strings.SplitN({{ if .CredPointer }}*{{ end }}payload.{{ .CredField }}, " ", 2)[1]
payload.{{ .CredField }} = {{ if .CredPointer }}&{{ end }}cred
}
{{- if not .CredRequired }}
}
{{- end }}
{{- end }}
return payload, nil
}
}
` + requestElementsT
// input: RequestData
const requestElementsT = `{{- define "request_elements" }}
{{- if or .PathParams .QueryParams .Headers .Cookies }}
{{- if .ServerBody }}{{/* we want a newline only if there was code before */}}
{{ end }}
var (
{{- range .PathParams }}
{{ .VarName }} {{ .TypeRef }}
{{- end }}
{{- range .QueryParams }}
{{ .VarName }} {{ .TypeRef }}
{{- end }}
{{- range .Headers }}
{{ .VarName }} {{ .TypeRef }}
{{- end }}
{{- range .Cookies }}
{{ .VarName }} {{ .TypeRef }}
{{- end }}
{{- if and .MustValidate (or (not .ServerBody) .Multipart) }}
err error
{{- end }}
{{- if .Cookies }}
c *http.Cookie
{{- end }}
{{- if .PathParams }}
params = mux.Vars(r)
{{- end }}
)
{{- range .PathParams }}
{{- if and (or (eq .Type.Name "string") (eq .Type.Name "any")) }}
{{ .VarName }} = params["{{ .Name }}"]
{{- else }}{{/* not string and not any */}}
{
{{ .VarName }}Raw := params["{{ .Name }}"]
{{- template "path_conversion" . }}
}
{{- end }}
{{- if .Validate }}
{{ .Validate }}
{{- end }}
{{- end }}
{{- range .QueryParams }}
{{- if and (or (eq .Type.Name "string") (eq .Type.Name "any")) .Required }}
{{ .VarName }} = r.URL.Query().Get("{{ .Name }}")
if {{ .VarName }} == "" {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "query string"))
}
{{- else if (or (eq .Type.Name "string") (eq .Type.Name "any")) }}
{{ .VarName }}Raw := r.URL.Query().Get("{{ .Name }}")
if {{ .VarName }}Raw != "" {
{{ .VarName }} = {{ if and (eq .Type.Name "string") .Pointer }}&{{ end }}{{ .VarName }}Raw
}
{{- if .DefaultValue }} else {
{{ .VarName }} = {{ if eq .Type.Name "string" }}{{ printf "%q" .DefaultValue }}{{ else }}{{ printf "%#v" .DefaultValue }}{{ end }}
}
{{- end }}
{{- else if .StringSlice }}
{{ .VarName }} = r.URL.Query()["{{ .Name }}"]
{{- if .Required }}
if {{ .VarName }} == nil {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "query string"))
}
{{- else if .DefaultValue }}
if {{ .VarName }} == nil {
{{ .VarName }} = []string{
{{- range $i, $v := .DefaultValue }}
{{- if $i }}{{ print ", " }}{{ end }}
{{- printf "%q" $v -}}
{{- end -}} }
}
{{- end }}
{{- else if .Slice }}
{
{{ .VarName }}Raw := r.URL.Query()["{{ .Name }}"]
{{- if .Required }}
if {{ .VarName }}Raw == nil {
return nil, goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "query string"))
}
{{- else if .DefaultValue }}
if {{ .VarName }}Raw == nil {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- if .DefaultValue }}else {
{{- else if not .Required }}
if {{ .VarName }}Raw != nil {
{{- end }}
{{- template "slice_conversion" . }}
{{- if or .DefaultValue (not .Required) }}
}
{{- end }}
}
{{- else if .Map }}
{
{{ .VarName }}Raw := r.URL.Query()
{{- if .Required }}
if len({{ .VarName }}Raw) == 0 {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "query string"))
}
{{- else if .DefaultValue }}
if len({{ .VarName }}Raw) == 0 {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- if .DefaultValue }}else {
{{- else if not .Required }}
if len({{ .VarName }}Raw) != 0 {
{{- end }}
for keyRaw, valRaw := range {{ .VarName }}Raw {
if strings.HasPrefix(keyRaw, "{{ .Name }}[") {
{{- template "map_conversion" (mapQueryDecodeData .Type .VarName 0) }}
}
}
{{- if or .DefaultValue (not .Required) }}
}
{{- end }}
}
{{- else if .MapQueryParams }}
{
{{ .VarName }}Raw := r.URL.Query()
{{- if .Required }}
if len({{ .VarName }}Raw) == 0 {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "query string"))
}
{{- else if .DefaultValue }}
if len({{ .VarName }}Raw) == 0 {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- if .DefaultValue }}else {
{{- else if not .Required }}
if len({{ .VarName }}Raw) != 0 {
{{- end }}
for keyRaw, valRaw := range {{ .VarName }}Raw {
if strings.HasPrefix(keyRaw, "{{ .Name }}[") {
{{- template "map_conversion" (mapQueryDecodeData .Type .VarName 0) }}
}
}
{{- if or .DefaultValue (not .Required) }}
}
{{- end }}
}
{{- else }}{{/* not string, not any, not slice and not map */}}
{
{{ .VarName }}Raw := r.URL.Query().Get("{{ .Name }}")
{{- if .Required }}
if {{ .VarName }}Raw == "" {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "query string"))
}
{{- else if .DefaultValue }}
if {{ .VarName }}Raw == "" {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- if .DefaultValue }}else {
{{- else if not .Required }}
if {{ .VarName }}Raw != "" {
{{- end }}
{{- template "type_conversion" . }}
{{- if or .DefaultValue (not .Required) }}
}
{{- end }}
}
{{- end }}
{{- if .Validate }}
{{ .Validate }}
{{- end }}
{{- end }}
{{- range .Headers }}
{{- if and (or (eq .Type.Name "string") (eq .Type.Name "any")) .Required }}
{{ .VarName }} = r.Header.Get("{{ .Name }}")
if {{ .VarName }} == "" {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "header"))
}
{{- else if (or (eq .Type.Name "string") (eq .Type.Name "any")) }}
{{ .VarName }}Raw := r.Header.Get("{{ .Name }}")
if {{ .VarName }}Raw != "" {
{{ .VarName }} = {{ if and (eq .Type.Name "string") .Pointer }}&{{ end }}{{ .VarName }}Raw
}
{{- if .DefaultValue }} else {
{{ .VarName }} = {{ if eq .Type.Name "string" }}{{ printf "%q" .DefaultValue }}{{ else }}{{ printf "%#v" .DefaultValue }}{{ end }}
}
{{- end }}
{{- else if .StringSlice }}
{{ .VarName }} = r.Header["{{ .CanonicalName }}"]
{{- if .Required }}
if {{ .VarName }} == nil {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "header"))
}
{{- else if .DefaultValue }}
if {{ .VarName }} == nil {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- else if .Slice }}
{
{{ .VarName }}Raw := r.Header["{{ .CanonicalName }}"]
{{ if .Required }}if {{ .VarName }}Raw == nil {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "header"))
}
{{- else if .DefaultValue }}
if {{ .VarName }}Raw == nil {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- if .DefaultValue }}else {
{{- else if not .Required }}
if {{ .VarName }}Raw != nil {
{{- end }}
{{- template "slice_conversion" . }}
{{- if or .DefaultValue (not .Required) }}
}
{{- end }}
}
{{- else }}{{/* not string, not any and not slice */}}
{
{{ .VarName }}Raw := r.Header.Get("{{ .Name }}")
{{- if .Required }}
if {{ .VarName }}Raw == "" {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "header"))
}
{{- else if .DefaultValue }}
if {{ .VarName }}Raw == "" {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- if .DefaultValue }}else {
{{- else if not .Required }}
if {{ .VarName }}Raw != "" {
{{- end }}
{{- template "type_conversion" . }}
{{- if or .DefaultValue (not .Required) }}
}
{{- end }}
}
{{- end }}
{{- if .Validate }}
{{ .Validate }}
{{- end }}
{{- end }}
{{- range .Cookies }}
c, {{ if not .Required }}_{{ else }}err{{ end }} = r.Cookie("{{ .Name }}")
{{- if and (or (eq .Type.Name "string") (eq .Type.Name "any")) .Required }}
if err == http.ErrNoCookie {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "cookie"))
} else {
{{ .VarName }} = c.Value
}
{{- else if (or (eq .Type.Name "string") (eq .Type.Name "any")) }}
var {{ .VarName }}Raw string
if c != nil {
{{ .VarName }}Raw = c.Value
}
if {{ .VarName }}Raw != "" {
{{ .VarName }} = {{ if and (eq .Type.Name "string") .Pointer }}&{{ end }}{{ .VarName }}Raw
}
{{- if .DefaultValue }} else {
{{ .VarName }} = {{ if eq .Type.Name "string" }}{{ printf "%q" .DefaultValue }}{{ else }}{{ printf "%#v" .DefaultValue }}{{ end }}
}
{{- end }}
{{- else }}{{/* not string and not any */}}
{
var {{ .VarName }}Raw string
if c != nil {
{{ .VarName }}Raw = c.Value
}
{{- if .Required }}
if {{ .VarName }}Raw == "" {
err = goa.MergeErrors(err, goa.MissingFieldError("{{ .Name }}", "cookie"))
}
{{- else if .DefaultValue }}
if {{ .VarName }}Raw == "" {
{{ .VarName }} = {{ printf "%#v" .DefaultValue }}
}
{{- end }}
{{- if .DefaultValue }}else {
{{- else if not .Required }}
if {{ .VarName }}Raw != "" {
{{- end }}
{{- template "type_conversion" . }}
{{- if or .DefaultValue (not .Required) }}
}
{{- end }}
}
{{- end }}
{{- if .Validate }}
{{ .Validate }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
{{- define "path_conversion" }}
{{- if eq .Type.Name "array" }}
{{ .VarName }}RawSlice := strings.Split({{ .VarName }}Raw, ",")
{{ .VarName }} = make({{ goTypeRef .Type }}, len({{ .VarName }}RawSlice))
for i, rv := range {{ .VarName }}RawSlice {
{{- template "slice_item_conversion" . }}
}
{{- else }}
{{- template "type_conversion" . }}
{{- end }}
{{- end }}
{{- define "map_conversion" }}
if {{ .VarName }} == nil {
{{ .VarName }} = make({{ goTypeRef .Type }})
}
var key{{ .Loop }} {{ goTypeRef .Type.KeyType.Type }}
{
openIdx := strings.IndexRune(keyRaw, '[')
closeIdx := strings.IndexRune(keyRaw, ']')
{{- if eq .Type.KeyType.Type.Name "string" }}
key{{ .Loop }} = keyRaw[openIdx+1 : closeIdx]
{{- else }}
key{{ .Loop }}Raw := keyRaw[openIdx+1 : closeIdx]
{{- template "type_conversion" (conversionData (printf "key%s" .Loop) (printf "%q" "query") .Type.KeyType.Type) }}
{{- end }}
{{- if gt .Depth 0 }}
keyRaw = keyRaw[closeIdx+1:]
{{- end }}
}
{{- if eq .Type.ElemType.Type.Name "string" }}
{{ .VarName }}[key{{ .Loop }}] = valRaw[0]
{{- else if eq .Type.ElemType.Type.Name "array" }}
{{- if eq .Type.ElemType.Type.ElemType.Type.Name "string" }}
{{ .VarName }}[key{{ .Loop }}] = valRaw
{{- else }}
var val {{ goTypeRef .Type.ElemType.Type }}
{
{{- template "slice_conversion" (conversionData "val" (printf "%q" "query") .Type.ElemType.Type) }}
}
{{ .VarName }}[key{{ .Loop }}] = val
{{- end }}
{{- else if eq .Type.ElemType.Type.Name "map" }}
{{- template "map_conversion" (mapQueryDecodeData .Type.ElemType.Type (printf "%s[key%s]" .VarName .Loop) 1) }}
{{- else }}
var val{{ .Loop }} {{ goTypeRef .Type.ElemType.Type }}
{
val{{ .Loop }}Raw := valRaw[0]
{{- template "type_conversion" (conversionData (printf "val%s" .Loop) (printf "%q" "query") .Type.ElemType.Type) }}
}
{{ .VarName }}[key{{ .Loop }}] = val{{ .Loop }}
{{- end }}
{{- end }}
` + typeConversionT
const typeConversionT = `{{- define "slice_conversion" }}
{{ .VarName }} = make({{ goTypeRef .Type }}, len({{ .VarName }}Raw))
for i, rv := range {{ .VarName }}Raw {
{{- template "slice_item_conversion" . }}