forked from xlab/goa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_data.go
2900 lines (2783 loc) · 94.2 KB
/
service_data.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 (
"bytes"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"text/template"
"goa.design/goa/codegen"
"goa.design/goa/codegen/service"
"goa.design/goa/expr"
)
// HTTPServices holds the data computed from the design needed to generate the
// transport code of the services.
var HTTPServices = make(ServicesData)
var (
// pathInitTmpl is the template used to render path constructors code.
pathInitTmpl = template.Must(template.New("path-init").Funcs(template.FuncMap{"goify": codegen.Goify}).Parse(pathInitT))
// requestInitTmpl is the template used to render request constructors.
requestInitTmpl = template.Must(template.New("request-init").Parse(requestInitT))
)
type (
// ServicesData encapsulates the data computed from the design.
ServicesData map[string]*ServiceData
// ServiceData contains the data used to render the code related to a
// single service.
ServiceData struct {
// Service contains the related service data.
Service *service.Data
// Endpoints describes the endpoint data for this service.
Endpoints []*EndpointData
// FileServers lists the file servers for this service.
FileServers []*FileServerData
// ServerStruct is the name of the HTTP server struct.
ServerStruct string
// MountPointStruct is the name of the mount point struct.
MountPointStruct string
// ServerInit is the name of the constructor of the server
// struct.
ServerInit string
// MountServer is the name of the mount function.
MountServer string
// ServerService is the name of service function.
ServerService string
// ClientStruct is the name of the HTTP client struct.
ClientStruct string
// ServerBodyAttributeTypes is the list of user types used to
// define the request, response and error response type
// attributes in the server code.
ServerBodyAttributeTypes []*TypeData
// ClientBodyAttributeTypes is the list of user types used to
// define the request, response and error response type
// attributes in the client code.
ClientBodyAttributeTypes []*TypeData
// ServerTypeNames records the user type names used to define
// the endpoint request and response bodies for server code.
// The type name is used as the key and a bool as the value
// which if true indicates that the type has been generated
// in the server package.
ServerTypeNames map[string]bool
// ClientTypeNames records the user type names used to define
// the endpoint request and response bodies for client code.
// The type name is used as the key and a bool as the value
// which if true indicates that the type has been generated
// in the client package.
ClientTypeNames map[string]bool
// ServerTransformHelpers is the list of transform functions
// required by the various server side constructors.
ServerTransformHelpers []*codegen.TransformFunctionData
// ClientTransformHelpers is the list of transform functions
// required by the various client side constructors.
ClientTransformHelpers []*codegen.TransformFunctionData
// Scope initialized with all the server and client types.
Scope *codegen.NameScope
}
// EndpointData contains the data used to render the code related to a
// single service HTTP endpoint.
EndpointData struct {
// Method contains the related service method data.
Method *service.MethodData
// ServiceName is the name of the service exposing the endpoint.
ServiceName string
// ServiceVarName is the goified service name (first letter
// lowercase).
ServiceVarName string
// ServicePkgName is the name of the service package.
ServicePkgName string
// Payload describes the method HTTP payload.
Payload *PayloadData
// Result describes the method HTTP result.
Result *ResultData
// Errors describes the method HTTP errors.
Errors []*ErrorGroupData
// Routes describes the possible routes for this endpoint.
Routes []*RouteData
// BasicScheme is the basic auth security scheme if any.
BasicScheme *service.SchemeData
// HeaderSchemes lists all the security requirement schemes that
// apply to the method and are encoded in the request header.
HeaderSchemes service.SchemesData
// BodySchemes lists all the security requirement schemes that
// apply to the method and are encoded in the request body.
BodySchemes service.SchemesData
// QuerySchemes lists all the security requirement schemes that
// apply to the method and are encoded in the request query
// string.
QuerySchemes service.SchemesData
// server
// MountHandler is the name of the mount handler function.
MountHandler string
// HandlerInit is the name of the constructor function for the
// http handler function.
HandlerInit string
// RequestDecoder is the name of the request decoder function.
RequestDecoder string
// ResponseEncoder is the name of the response encoder function.
ResponseEncoder string
// ErrorEncoder is the name of the error encoder function.
ErrorEncoder string
// MultipartRequestDecoder indicates the request decoder for
// multipart content type.
MultipartRequestDecoder *MultipartData
// ServerStream holds the data to render the server struct which
// implements the server stream interface.
ServerStream *StreamData
// client
// ClientStruct is the name of the HTTP client struct.
ClientStruct string
// EndpointInit is the name of the constructor function for the
// client endpoint.
EndpointInit string
// RequestInit is the request builder function.
RequestInit *InitData
// RequestEncoder is the name of the request encoder function.
RequestEncoder string
// ResponseDecoder is the name of the response decoder function.
ResponseDecoder string
// MultipartRequestEncoder indicates the request encoder for
// multipart content type.
MultipartRequestEncoder *MultipartData
// ClientStream holds the data to render the client struct which
// implements the client stream interface.
ClientStream *StreamData
}
// FileServerData lists the data needed to generate file servers.
FileServerData struct {
// MountHandler is the name of the mount handler function.
MountHandler string
// RequestPaths is the set of HTTP paths to the server.
RequestPaths []string
// Root is the root server file path.
FilePath string
// Dir is true if the file server servers files under a
// directory, false if it serves a single file.
IsDir bool
// PathParam is the name of the parameter used to capture the
// path for file servers that serve files under a directory.
PathParam string
}
// PayloadData contains the payload information required to generate the
// transport decode (server) and encode (client) code.
PayloadData struct {
// Name is the name of the payload type.
Name string
// Ref is the fully qualified reference to the payload type.
Ref string
// Request contains the data for the corresponding HTTP request.
Request *RequestData
// DecoderReturnValue is a reference to the decoder return value
// if there is no payload constructor (i.e. if Init is nil).
DecoderReturnValue string
}
// ResultData contains the result information required to generate the
// transport decode (client) and encode (server) code.
ResultData struct {
// Name is the name of the result type.
Name string
// Ref is the reference to the result type.
Ref string
// IsStruct is true if the result type is a user type defining
// an object.
IsStruct bool
// Inits contains the data required to render the result
// constructors if any.
Inits []*InitData
// Responses contains the data for the corresponding HTTP
// responses.
Responses []*ResponseData
// View is the view used to render the result.
View string
// MustInit indicates if a variable holding the result type must be
// initialized. It is used by server response encoder to initialize
// the result variable only if there are multiple responses, or the
// response has a body or a header.
MustInit bool
}
// ErrorGroupData contains the error information required to generate
// the transport decode (client) and encode (server) code for all errors
// with responses using a given HTTP status code.
ErrorGroupData struct {
// StatusCode is the response HTTP status code.
StatusCode string
// Errors contains the information for each error.
Errors []*ErrorData
}
// ErrorData contains the error information required to generate the
// transport decode (client) and encode (server) code.
ErrorData struct {
// Name is the error name.
Name string
// Ref is a reference to the error type.
Ref string
// Response is the error response data.
Response *ResponseData
}
// RequestData describes a request.
RequestData struct {
// PathParams describes the information about params that are
// present in the request path.
PathParams []*ParamData
// QueryParams describes the information about the params that
// are present in the request query string.
QueryParams []*ParamData
// Headers contains the HTTP request headers used to build the
// method payload.
Headers []*HeaderData
// ServerBody describes the request body type used by server
// code. The type is generated using pointers for all fields so
// that it can be validated.
ServerBody *TypeData
// ClientBody describes the request body type used by client
// code. The type does NOT use pointers for every fields since
// no validation is required.
ClientBody *TypeData
// PayloadInit contains the data required to render the
// payload constructor used by server code if any.
PayloadInit *InitData
// MustValidate is true if the request body or at least one
// parameter or header requires validation.
MustValidate bool
// Multipart if true indicates the request is a multipart
// request.
Multipart bool
}
// ResponseData describes a response.
ResponseData struct {
// StatusCode is the return code of the response.
StatusCode string
// Description is the response description.
Description string
// Headers provides information about the headers in the
// response.
Headers []*HeaderData
// ContentType contains the value of the response
// "Content-Type" header.
ContentType string
// ErrorHeader contains the value of the response "goa-error"
// header if any.
ErrorHeader string
// ServerBody is the type of the response body used by server
// code, nil if body should be empty. The type does NOT use
// pointers for all fields. If the method result is a result
// type and the response data describes a success response, then
// this field contains a type for every view in the result type.
// The type name is suffixed with the name of the view (except
// for "default" view where no suffix is added). A constructor
// is also generated server side for each view to transform the
// result type to the corresponding response body type. If
// method result is not a result type or if the response
// describes an error response, then this field contains at most
// one item.
ServerBody []*TypeData
// ClientBody is the type of the response body used by client
// code, nil if body should be empty. The type uses pointers for
// all fields so they can be validated.
ClientBody *TypeData
// Init contains the data required to render the result or error
// constructor if any.
ResultInit *InitData
// TagName is the name of the attribute used to test whether the
// response is the one to use.
TagName string
// TagValue is the value the result attribute named by TagName
// must have for this response to be used.
TagValue string
// TagPointer is true if the tag attribute is a pointer.
TagPointer bool
// MustValidate is true if at least one header requires validation.
MustValidate bool
// ResultAttr sets the response body from the specified result
// type attribute. This field is set when the design uses
// Body("name") syntax to set the response body and the result
// type is an object.
ResultAttr string
// ViewedResult indicates whether the response body type is a
// result type.
ViewedResult *service.ViewedResultTypeData
}
// InitData contains the data required to render a constructor.
InitData struct {
// Name is the constructor function name.
Name string
// Description is the function description.
Description string
// ServerArgs is the list of constructor arguments for server
// side code.
ServerArgs []*InitArgData
// ClientArgs is the list of constructor arguments for client
// side code.
ClientArgs []*InitArgData
// CLIArgs is the list of arguments that should be initialized
// from CLI flags. This is used for implicit attributes which
// as the time of writing is only used for the basic auth
// username and password.
CLIArgs []*InitArgData
// ReturnTypeName is the qualified (including the package name)
// name of the payload, result or error type.
ReturnTypeName string
// ReturnTypeRef is the qualified (including the package name)
// reference to the payload, result or error type.
ReturnTypeRef string
// ReturnTypeAttribute is the name of the attribute initialized
// by this constructor when it only initializes one attribute
// (i.e. body was defined with Body("name") syntax).
ReturnTypeAttribute string
// ReturnIsStruct is true if the return type is a struct.
ReturnIsStruct bool
// ReturnIsPrimitivePointer indicates whether the return type is
// a primitive pointer.
ReturnIsPrimitivePointer bool
// ServerCode is the code that builds the payload from the
// request on the server when it contains user types.
ServerCode string
// ClientCode is the code that builds the payload or result type
// from the request or response state on the client when it
// contains user types.
ClientCode string
}
// InitArgData represents a single constructor argument.
InitArgData struct {
// Name is the argument name.
Name string
// Description is the argument description.
Description string
// Reference to the argument, e.g. "&body".
Ref string
// FieldName is the name of the data structure field that should
// be initialized with the argument if any.
FieldName string
// FieldPointer if true indicates that the data structure field is a
// pointer.
FieldPointer bool
// TypeName is the argument type name.
TypeName string
// TypeRef is the argument type reference.
TypeRef string
// Pointer is true if a pointer to the arg should be used.
Pointer bool
// Required is true if the arg is required to build the payload.
Required bool
// DefaultValue is the default value of the arg.
DefaultValue interface{}
// Validate contains the validation code for the argument
// value if any.
Validate string
// Example is a example value
Example interface{}
}
// RouteData describes a route.
RouteData struct {
// Verb is the HTTP method.
Verb string
// Path is the fullpath including wildcards.
Path string
// PathInit contains the information needed to render and call
// the path constructor for the route.
PathInit *InitData
}
// ParamData describes a HTTP request parameter.
ParamData struct {
// Name is the name of the mapping to the actual variable name.
Name string
// AttributeName is the name of the corresponding attribute.
AttributeName string
// Description is the parameter description
Description string
// FieldName is the name of the struct field that holds the
// param value.
FieldName string
// FieldPointer if true indicates that the struct field that holds the
// param value is a pointer.
FieldPointer bool
// VarName is the name of the Go variable used to read or
// convert the param value.
VarName string
// ServiceField is true if there is a corresponding attribute in
// the service types.
ServiceField bool
// Type is the datatype of the variable.
Type expr.DataType
// TypeName is the name of the type.
TypeName string
// TypeRef is the reference to the type.
TypeRef string
// Required is true if the param is required.
Required bool
// Pointer is true if and only the param variable is a pointer.
Pointer bool
// StringSlice is true if the param type is array of strings.
StringSlice bool
// Slice is true if the param type is an array.
Slice bool
// MapStringSlice is true if the param type is a map of string
// slice.
MapStringSlice bool
// Map is true if the param type is a map.
Map bool
// Validate contains the validation code if any.
Validate string
// DefaultValue contains the default value if any.
DefaultValue interface{}
// Example is an example value.
Example interface{}
// MapQueryParams indicates that the query params must be mapped
// to the entire payload (empty string) or a payload attribute
// (attribute name).
MapQueryParams *string
}
// HeaderData describes a HTTP request or response header.
HeaderData struct {
// Name is the name of the header key.
Name string
// AttributeName is the name of the corresponding attribute.
AttributeName string
// Description is the header description.
Description string
// CanonicalName is the canonical header key.
CanonicalName string
// FieldName is the name of the struct field that holds the
// header value if any, empty string otherwise.
FieldName string
// FieldPointer if true indicates that the struct field that holds the
// header value is a pointer.
FieldPointer bool
// VarName is the name of the Go variable used to read or
// convert the header value.
VarName string
// TypeName is the name of the type.
TypeName string
// TypeRef is the reference to the type.
TypeRef string
// Required is true if the header is required.
Required bool
// Pointer is true if and only the param variable is a pointer.
Pointer bool
// StringSlice is true if the param type is array of strings.
StringSlice bool
// Slice is true if the param type is an array.
Slice bool
// Type describes the datatype of the variable value. Mainly
// used for conversion.
Type expr.DataType
// Validate contains the validation code if any.
Validate string
// DefaultValue contains the default value if any.
DefaultValue interface{}
// Example is an example value.
Example interface{}
}
// TypeData contains the data needed to render a type definition.
TypeData struct {
// Name is the type name.
Name string
// VarName is the Go type name.
VarName string
// Description is the type human description.
Description string
// Init contains the data needed to render and call the type
// constructor if any.
Init *InitData
// Def is the type definition Go code.
Def string
// Ref is the reference to the type.
Ref string
// ValidateDef contains the validation code.
ValidateDef string
// ValidateRef contains the call to the validation code.
ValidateRef string
// Example is an example value for the type.
Example interface{}
// View is the view using which the type is rendered.
View string
}
// MultipartData contains the data needed to render multipart
// encoder/decoder.
MultipartData struct {
// FuncName is the name used to generate function type.
FuncName string
// InitName is the name of the constructor.
InitName string
// VarName is the name of the variable referring to the function.
VarName string
// ServiceName is the name of the service.
ServiceName string
// MethodName is the name of the method.
MethodName string
// Payload is the payload data required to generate
// encoder/decoder.
Payload *PayloadData
}
// StreamData contains the data needed to render struct type that
// implements the server and client stream interfaces.
StreamData struct {
// VarName is the name of the struct.
VarName string
// Type is type of the stream (server or client).
Type string
// Interface is the fully qualified name of the interface that
// the struct implements.
Interface string
// Endpoint is endpoint data that defines streaming
// payload/result.
Endpoint *EndpointData
// Payload is the streaming payload type sent via the stream.
Payload *TypeData
// Response is the successful response data for the streaming
// endpoint.
Response *ResponseData
// SendName is the name of the send function.
SendName string
// SendDesc is the description for the send function.
SendDesc string
// SendTypeName is the fully qualified type name sent through
// the stream.
SendTypeName string
// SendTypeRef is the fully qualified type ref sent through the
// stream.
SendTypeRef string
// RecvName is the name of the receive function.
RecvName string
// RecvDesc is the description for the recv function.
RecvDesc string
// RecvTypeName is the fully qualified type name received from
// the stream.
RecvTypeName string
// RecvTypeRef is the fully qualified type ref received from the
// stream.
RecvTypeRef string
// MustClose indicates whether to generate the Close() function
// for the stream.
MustClose bool
// PkgName is the service package name.
PkgName string
// Kind is the kind of the stream (payload, result or
// bidirectional).
Kind expr.StreamKind
}
)
// Get retrieves the transport data for the service with the given name
// computing it if needed. It returns nil if there is no service with the given
// name.
func (d ServicesData) Get(name string) *ServiceData {
if data, ok := d[name]; ok {
return data
}
service := expr.Root.API.HTTP.Service(name)
if service == nil {
return nil
}
d[name] = d.analyze(service)
return d[name]
}
// Endpoint returns the service method transport data for the endpoint with the
// given name, nil if there isn't one.
func (svc *ServiceData) Endpoint(name string) *EndpointData {
for _, e := range svc.Endpoints {
if e.Method.Name == name {
return e
}
}
return nil
}
// analyze creates the data necessary to render the code of the given service.
// It records the user types needed by the service definition in userTypes.
func (d ServicesData) analyze(hs *expr.HTTPServiceExpr) *ServiceData {
svc := service.Services.Get(hs.ServiceExpr.Name)
scope := codegen.NewNameScope()
scope.Unique("c") // 'c' is reserved as the client's receiver name.
scope.Unique("v") // 'v' is reserved as the request builder payload argument name.
rd := &ServiceData{
Service: svc,
ServerStruct: "Server",
MountPointStruct: "MountPoint",
ServerInit: "New",
MountServer: "Mount",
ServerService: "Service",
ClientStruct: "Client",
ServerTypeNames: make(map[string]bool),
ClientTypeNames: make(map[string]bool),
Scope: scope,
}
for _, s := range hs.FileServers {
paths := make([]string, len(s.RequestPaths))
for i, p := range s.RequestPaths {
idx := strings.LastIndex(p, "/{")
if idx > 0 {
paths[i] = p[:idx]
} else {
paths[i] = p
}
}
var pp string
if s.IsDir() {
pp = expr.ExtractHTTPWildcards(s.RequestPaths[0])[0]
}
data := &FileServerData{
MountHandler: fmt.Sprintf("Mount%s", codegen.Goify(s.FilePath, true)),
RequestPaths: paths,
FilePath: s.FilePath,
IsDir: s.IsDir(),
PathParam: pp,
}
rd.FileServers = append(rd.FileServers, data)
}
for _, a := range hs.HTTPEndpoints {
ep := svc.Method(a.MethodExpr.Name)
var routes []*RouteData
i := 0
for _, r := range a.Routes {
for _, rpath := range r.FullPaths() {
params := expr.ExtractHTTPWildcards(rpath)
var (
init *InitData
)
{
initArgs := make([]*InitArgData, len(params))
pathParamsObj := expr.AsObject(a.PathParams().Type)
suffix := ""
if i > 0 {
suffix = strconv.Itoa(i + 1)
}
i++
name := fmt.Sprintf("%s%sPath%s", ep.VarName, svc.StructName, suffix)
for j, arg := range params {
att := pathParamsObj.Attribute(arg)
pointer := a.Params.IsPrimitivePointer(arg, true)
name := rd.Scope.Name(codegen.Goify(arg, false))
var vcode string
if att.Validation != nil {
ctx := httpContext("", rd.Scope, true, false)
vcode = codegen.RecursiveValidationCode(att, ctx, true, name)
}
initArgs[j] = &InitArgData{
Name: name,
Description: att.Description,
Ref: name,
FieldName: codegen.Goify(arg, true),
TypeName: rd.Scope.GoTypeName(att),
TypeRef: rd.Scope.GoTypeRef(att),
Pointer: pointer,
Required: true,
Example: att.Example(expr.Root.API.Random()),
Validate: vcode,
}
}
var buffer bytes.Buffer
pf := expr.HTTPWildcardRegex.ReplaceAllString(rpath, "/%v")
err := pathInitTmpl.Execute(&buffer, map[string]interface{}{
"Args": initArgs,
"PathParams": pathParamsObj,
"PathFormat": pf,
})
if err != nil {
panic(err)
}
init = &InitData{
Name: name,
Description: fmt.Sprintf("%s returns the URL path to the %s service %s HTTP endpoint. ", name, svc.Name, ep.Name),
ServerArgs: initArgs,
ClientArgs: initArgs,
ReturnTypeName: "string",
ReturnTypeRef: "string",
ServerCode: buffer.String(),
ClientCode: buffer.String(),
}
}
routes = append(routes, &RouteData{
Verb: strings.ToUpper(r.Method),
Path: rpath,
PathInit: init,
})
}
}
payload := buildPayloadData(a, rd)
var (
hsch service.SchemesData
bosch service.SchemesData
qsch service.SchemesData
basch *service.SchemeData
)
{
for _, req := range ep.Requirements {
for _, s := range req.Schemes {
switch s.Type {
case "Basic":
basch = s
default:
switch s.In {
case "query":
qsch = qsch.Append(s)
case "header":
hsch = hsch.Append(s)
default:
bosch = bosch.Append(s)
}
}
}
}
}
var requestEncoder string
{
if payload.Request.ClientBody != nil || len(payload.Request.Headers) > 0 || len(payload.Request.QueryParams) > 0 || basch != nil {
requestEncoder = fmt.Sprintf("Encode%sRequest", ep.VarName)
}
}
var requestInit *InitData
{
var (
name string
args []*InitArgData
payloadRef string
)
{
name = fmt.Sprintf("Build%sRequest", ep.VarName)
s := codegen.NewNameScope()
for _, ca := range routes[0].PathInit.ClientArgs {
if ca.FieldName != "" {
ca.Name = s.Unique(ca.Name)
ca.Ref = ca.Name
args = append(args, ca)
}
}
if len(routes[0].PathInit.ClientArgs) > 0 && a.MethodExpr.Payload.Type != expr.Empty {
payloadRef = svc.Scope.GoFullTypeRef(a.MethodExpr.Payload, svc.PkgName)
}
}
data := map[string]interface{}{
"PayloadRef": payloadRef,
"HasFields": expr.IsObject(a.MethodExpr.Payload.Type),
"ServiceName": svc.Name,
"EndpointName": ep.Name,
"Args": args,
"PathInit": routes[0].PathInit,
"Verb": routes[0].Verb,
"IsStreaming": a.MethodExpr.IsStreaming(),
}
var buf bytes.Buffer
if err := requestInitTmpl.Execute(&buf, data); err != nil {
panic(err) // bug
}
requestInit = &InitData{
Name: name,
Description: fmt.Sprintf("%s instantiates a HTTP request object with method and path set to call the %q service %q endpoint", name, svc.Name, ep.Name),
ClientCode: buf.String(),
ClientArgs: []*InitArgData{{
Name: "v",
Ref: "v",
TypeRef: "interface{}",
}},
}
}
ad := &EndpointData{
Method: ep,
ServiceName: svc.Name,
ServiceVarName: svc.VarName,
ServicePkgName: svc.PkgName,
Payload: payload,
Result: buildResultData(a, rd),
Errors: buildErrorsData(a, rd),
HeaderSchemes: hsch,
BodySchemes: bosch,
QuerySchemes: qsch,
BasicScheme: basch,
Routes: routes,
MountHandler: fmt.Sprintf("Mount%sHandler", ep.VarName),
HandlerInit: fmt.Sprintf("New%sHandler", ep.VarName),
RequestDecoder: fmt.Sprintf("Decode%sRequest", ep.VarName),
ResponseEncoder: fmt.Sprintf("Encode%sResponse", ep.VarName),
ErrorEncoder: fmt.Sprintf("Encode%sError", ep.VarName),
ClientStruct: "Client",
EndpointInit: ep.VarName,
RequestInit: requestInit,
RequestEncoder: requestEncoder,
ResponseDecoder: fmt.Sprintf("Decode%sResponse", ep.VarName),
}
buildStreamData(ad, a, rd)
if a.MultipartRequest {
ad.MultipartRequestDecoder = &MultipartData{
FuncName: fmt.Sprintf("%s%sDecoderFunc", svc.StructName, ep.VarName),
InitName: fmt.Sprintf("New%s%sDecoder", svc.StructName, ep.VarName),
VarName: fmt.Sprintf("%s%sDecoderFn", svc.VarName, ep.VarName),
ServiceName: svc.Name,
MethodName: ep.Name,
Payload: ad.Payload,
}
ad.MultipartRequestEncoder = &MultipartData{
FuncName: fmt.Sprintf("%s%sEncoderFunc", svc.StructName, ep.VarName),
InitName: fmt.Sprintf("New%s%sEncoder", svc.StructName, ep.VarName),
VarName: fmt.Sprintf("%s%sEncoderFn", svc.VarName, ep.VarName),
ServiceName: svc.Name,
MethodName: ep.Name,
Payload: ad.Payload,
}
}
rd.Endpoints = append(rd.Endpoints, ad)
}
for _, a := range hs.HTTPEndpoints {
collectUserTypes(a.Body.Type, func(ut expr.UserType) {
if d := attributeTypeData(ut, true, true, true, rd); d != nil {
rd.ServerBodyAttributeTypes = append(rd.ServerBodyAttributeTypes, d)
}
if d := attributeTypeData(ut, true, false, false, rd); d != nil {
rd.ClientBodyAttributeTypes = append(rd.ClientBodyAttributeTypes, d)
}
})
if a.MethodExpr.StreamingPayload.Type != expr.Empty {
collectUserTypes(a.StreamingBody.Type, func(ut expr.UserType) {
if d := attributeTypeData(ut, true, true, true, rd); d != nil {
rd.ServerBodyAttributeTypes = append(rd.ServerBodyAttributeTypes, d)
}
if d := attributeTypeData(ut, true, false, false, rd); d != nil {
rd.ClientBodyAttributeTypes = append(rd.ClientBodyAttributeTypes, d)
}
})
}
if res := a.MethodExpr.Result; res != nil {
for _, v := range a.Responses {
collectUserTypes(v.Body.Type, func(ut expr.UserType) {
// NOTE: ServerBodyAttributeTypes for response body types are
// collected in buildResponseBodyType because we have to generate
// body types for each view in a result type.
if d := attributeTypeData(ut, false, true, false, rd); d != nil {
rd.ClientBodyAttributeTypes = append(rd.ClientBodyAttributeTypes, d)
}
})
}
}
for _, v := range a.HTTPErrors {
collectUserTypes(v.Response.Body.Type, func(ut expr.UserType) {
// NOTE: ServerBodyAttributeTypes for error response body types are
// collected in buildResponseBodyType because we have to generate
// body types for each view in a result type.
if d := attributeTypeData(ut, false, true, false, rd); d != nil {
rd.ClientBodyAttributeTypes = append(rd.ClientBodyAttributeTypes, d)
}
})
}
}
return rd
}
// buildPayloadData returns the data structure used to describe the endpoint
// payload including the HTTP request details. It also returns the user types
// used by the request body type recursively if any.
func buildPayloadData(e *expr.HTTPEndpointExpr, sd *ServiceData) *PayloadData {
var (
payload = e.MethodExpr.Payload
svc = sd.Service
body = e.Body.Type
ep = svc.Method(e.MethodExpr.Name)
httpsvrctx = httpContext("", sd.Scope, true, true)
httpclictx = httpContext("", sd.Scope, true, false)
svcctx = serviceContext(sd.Service.PkgName, sd.Service.Scope)
request *RequestData
mapQueryParam *ParamData
)
{
var (
serverBodyData = buildRequestBodyType(e.Body, payload, e, true, sd)
clientBodyData = buildRequestBodyType(e.Body, payload, e, false, sd)
paramsData = extractPathParams(e.PathParams(), payload, sd.Scope)
queryData = extractQueryParams(e.QueryParams(), payload, sd.Scope)
headersData = extractHeaders(e.Headers, payload, svcctx, sd.Scope)
mustValidate bool
)
{
if e.MapQueryParams != nil {
var (
fieldName string
name = "query"
required = true
pAtt = payload
)
if n := *e.MapQueryParams; n != "" {
pAtt = expr.AsObject(payload.Type).Attribute(n)
required = payload.IsRequired(n)
name = n
fieldName = codegen.Goify(name, true)
}
varn := codegen.Goify(name, false)
mapQueryParam = &ParamData{
Name: name,
VarName: varn,
FieldName: fieldName,
Required: required,
Type: pAtt.Type,
TypeName: sd.Scope.GoTypeName(pAtt),
TypeRef: sd.Scope.GoTypeRef(pAtt),
Map: expr.AsMap(payload.Type) != nil,
Validate: codegen.RecursiveValidationCode(pAtt, httpsvrctx, required, varn),
DefaultValue: pAtt.DefaultValue,
Example: pAtt.Example(expr.Root.API.Random()),
MapQueryParams: e.MapQueryParams,
}
queryData = append(queryData, mapQueryParam)
}
if serverBodyData != nil {
sd.ServerTypeNames[serverBodyData.Name] = false
sd.ClientTypeNames[serverBodyData.Name] = false
}
for _, p := range paramsData {
if p.Validate != "" || needConversion(p.Type) {
mustValidate = true
break
}
}
if !mustValidate {
for _, q := range queryData {
if q.Validate != "" || q.Required || needConversion(q.Type) {
mustValidate = true
break
}
}
}
if !mustValidate {
for _, h := range headersData {
if h.Validate != "" || h.Required || needConversion(h.Type) {
mustValidate = true
break
}
}
}
}
request = &RequestData{
PathParams: paramsData,
QueryParams: queryData,
Headers: headersData,
ServerBody: serverBodyData,
ClientBody: clientBodyData,
MustValidate: mustValidate,
Multipart: e.MultipartRequest,