-
-
Notifications
You must be signed in to change notification settings - Fork 561
/
server.go
280 lines (259 loc) Β· 9.55 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
package codegen
import (
"fmt"
"path"
"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
fpath := filepath.Join(codegen.Gendir, "http", svcName, "server", "server.go")
title := fmt.Sprintf("%s HTTP server", svc.Name())
funcs := map[string]any{
"join": strings.Join,
"hasWebSocket": hasWebSocket,
"isWebSocketEndpoint": isWebSocketEndpoint,
"viewedServerBody": viewedServerBody,
"mustDecodeRequest": mustDecodeRequest,
"addLeadingSlash": addLeadingSlash,
"dir": path.Dir,
}
imports := []*codegen.ImportSpec{
{Path: "bufio"},
{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},
}
imports = append(imports, data.Service.UserTypeImports...)
sections := []*codegen.SectionTemplate{
codegen.Header(title, "server", imports),
}
sections = append(sections, &codegen.SectionTemplate{Name: "server-struct", Source: readTemplate("server_struct"), Data: data})
sections = append(sections, &codegen.SectionTemplate{Name: "server-mountpoint", Source: readTemplate("mount_point_struct"), Data: data})
for _, e := range data.Endpoints {
if e.MultipartRequestDecoder != nil {
sections = append(sections, &codegen.SectionTemplate{
Name: "multipart-request-decoder-type",
Source: readTemplate("multipart_request_decoder_type"),
Data: e.MultipartRequestDecoder,
})
}
}
sections = append(sections, &codegen.SectionTemplate{Name: "server-init", Source: readTemplate("server_init"), Data: data, FuncMap: funcs})
sections = append(sections, &codegen.SectionTemplate{Name: "server-service", Source: readTemplate("server_service"), Data: data})
sections = append(sections, &codegen.SectionTemplate{Name: "server-use", Source: readTemplate("server_use"), Data: data})
sections = append(sections, &codegen.SectionTemplate{Name: "server-method-names", Source: readTemplate("server_method_names"), Data: data})
sections = append(sections, &codegen.SectionTemplate{Name: "server-mount", Source: readTemplate("server_mount"), Data: data, FuncMap: funcs})
for _, e := range data.Endpoints {
sections = append(sections, &codegen.SectionTemplate{Name: "server-handler", Source: readTemplate("server_handler"), Data: e})
sections = append(sections, &codegen.SectionTemplate{Name: "server-handler-init", Source: readTemplate("server_handler_init"), FuncMap: funcs, Data: e})
}
if len(data.FileServers) > 0 {
mappedFiles := make(map[string]string)
for _, fs := range data.FileServers {
if !fs.IsDir {
for _, p := range fs.RequestPaths {
baseFilePath := "/" + filepath.Base(fs.FilePath)
baseRequestPath := "/" + filepath.Base(p)
if baseFilePath == baseRequestPath {
continue
}
mappedFiles[baseRequestPath] = baseFilePath
}
}
}
sections = append(sections, &codegen.SectionTemplate{Name: "append-fs", Source: readTemplate("append_fs"), FuncMap: funcs, Data: mappedFiles})
}
for _, s := range data.FileServers {
sections = append(sections, &codegen.SectionTemplate{Name: "server-files", Source: readTemplate("file_server"), FuncMap: funcs, Data: s})
}
return &codegen.File{Path: fpath, 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: readTemplate("response_encoder", "response", "header_conversion"),
Data: e,
})
}
if mustDecodeRequest(e) {
fm := transTmplFuncs(svc)
fm["mapQueryDecodeData"] = mapQueryDecodeData
sections = append(sections, &codegen.SectionTemplate{
Name: "request-decoder",
Source: readTemplate("request_decoder", "request_elements", "slice_item_conversion", "element_slice_conversion", "query_slice_conversion", "query_type_conversion", "query_map_conversion", "path_conversion"),
FuncMap: fm,
Data: e,
})
}
if e.MultipartRequestDecoder != nil {
fm := transTmplFuncs(svc)
fm["mapQueryDecodeData"] = mapQueryDecodeData
sections = append(sections, &codegen.SectionTemplate{
Name: "multipart-request-decoder",
Source: readTemplate("multipart_request_decoder", "request_elements", "slice_item_conversion", "element_slice_conversion", "query_slice_conversion", "query_type_conversion", "query_map_conversion", "path_conversion"),
FuncMap: fm,
Data: e.MultipartRequestDecoder,
})
}
if len(e.Errors) > 0 {
sections = append(sections, &codegen.SectionTemplate{
Name: "error-encoder",
Source: readTemplate("error_encoder", "response", "header_conversion"),
FuncMap: transTmplFuncs(svc),
Data: e,
})
}
}
for _, h := range data.ServerTransformHelpers {
sections = append(sections, &codegen.SectionTemplate{
Name: "server-transform-helper",
Source: readTemplate("transform_helper"),
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]any {
return map[string]any{
"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]any {
return map[string]any{
"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]any {
return map[string]any{
"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 any) 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 mapQueryDecodeData(dt expr.DataType, varName string, inc int) map[string]any {
return map[string]any{
"Type": dt,
"VarName": varName,
"Loop": string(rune(97 + inc)),
"Increment": inc + 1,
"Depth": codegen.MapDepth(expr.AsMap(dt)),
}
}