-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathexample_server.go
325 lines (297 loc) Β· 9.9 KB
/
example_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
package codegen
import (
"os"
"path"
"path/filepath"
"strings"
"goa.design/goa/codegen"
"goa.design/goa/codegen/example"
"goa.design/goa/expr"
)
// ExampleServerFiles returns an example http service implementation.
func ExampleServerFiles(genpkg string, root *expr.RootExpr) []*codegen.File {
var fw []*codegen.File
for _, svr := range root.API.Servers {
if m := exampleServer(genpkg, root, svr); m != nil {
fw = append(fw, m)
}
}
for _, svc := range root.API.HTTP.Services {
if f := dummyMultipartFile(genpkg, root, svc); f != nil {
fw = append(fw, f)
}
}
return fw
}
// exampleServer returns an example HTTP server implementation.
func exampleServer(genpkg string, root *expr.RootExpr, svr *expr.ServerExpr) *codegen.File {
svrdata := example.Servers.Get(svr)
fpath := filepath.Join("cmd", svrdata.Dir, "http.go")
specs := []*codegen.ImportSpec{
{Path: "context"},
{Path: "log"},
{Path: "net/http"},
{Path: "net/url"},
{Path: "os"},
{Path: "sync"},
{Path: "time"},
{Path: "goa.design/goa/http", Name: "goahttp"},
{Path: "goa.design/goa/middleware"},
{Path: "goa.design/goa/http/middleware", Name: "httpmdlwr"},
{Path: "github.com/gorilla/websocket"},
}
scope := codegen.NewNameScope()
for _, svc := range root.API.HTTP.Services {
sd := HTTPServices.Get(svc.Name())
svcName := codegen.SnakeCase(sd.Service.VarName)
specs = append(specs, &codegen.ImportSpec{
Path: path.Join(genpkg, "http", svcName, "server"),
Name: scope.Unique(sd.Service.PkgName + "svr"),
})
specs = append(specs, &codegen.ImportSpec{
Path: path.Join(genpkg, svcName),
Name: scope.Unique(sd.Service.PkgName),
})
}
var (
rootPath string
apiPkg string
)
{
// genpkg is created by path.Join so the separator is / regardless of operating system
idx := strings.LastIndex(genpkg, string("/"))
rootPath = "."
if idx > 0 {
rootPath = genpkg[:idx]
}
apiPkg = scope.Unique(strings.ToLower(codegen.Goify(root.API.Name, false)), "api")
}
specs = append(specs, &codegen.ImportSpec{Path: rootPath, Name: apiPkg})
var svcdata []*ServiceData
for _, svc := range svr.Services {
if data := HTTPServices.Get(svc); data != nil {
svcdata = append(svcdata, data)
}
}
sections := []*codegen.SectionTemplate{
codegen.Header("", "main", specs),
&codegen.SectionTemplate{
Name: "server-http-start",
Source: httpSvrStartT,
Data: map[string]interface{}{
"Services": svcdata,
},
},
&codegen.SectionTemplate{Name: "server-http-logger", Source: httpSvrLoggerT},
&codegen.SectionTemplate{Name: "server-http-encoding", Source: httpSvrEncodingT},
&codegen.SectionTemplate{Name: "server-http-mux", Source: httpSvrMuxT},
&codegen.SectionTemplate{
Name: "server-http-init",
Source: httpSvrInitT,
Data: map[string]interface{}{
"Services": svcdata,
"APIPkg": apiPkg,
},
FuncMap: map[string]interface{}{"needStream": needStream, "hasStreaming": hasStreaming},
},
&codegen.SectionTemplate{Name: "server-http-middleware", Source: httpSvrMiddlewareT},
&codegen.SectionTemplate{
Name: "server-http-end",
Source: httpSvrEndT,
Data: map[string]interface{}{
"Services": svcdata,
},
},
&codegen.SectionTemplate{Name: "server-http-errorhandler", Source: httpSvrErrorHandlerT},
}
return &codegen.File{Path: fpath, SectionTemplates: sections, SkipExist: true}
}
// dummyMultipartFile returns a dummy implementation of the multipart decoders
// and encoders.
func dummyMultipartFile(genpkg string, root *expr.RootExpr, svc *expr.HTTPServiceExpr) *codegen.File {
mpath := "multipart.go"
if _, err := os.Stat(mpath); !os.IsNotExist(err) {
return nil // file already exists, skip it.
}
var (
sections []*codegen.SectionTemplate
mustGen bool
scope = codegen.NewNameScope()
)
// determine the unique API package name different from the service names
for _, svc := range root.Services {
s := HTTPServices.Get(svc.Name)
if s == nil {
panic("unknown http service, " + svc.Name) // bug
}
if s.Service == nil {
panic("unknown service, " + svc.Name) // bug
}
scope.Unique(s.Service.PkgName)
}
{
specs := []*codegen.ImportSpec{
{Path: "mime/multipart"},
}
data := HTTPServices.Get(svc.Name())
specs = append(specs, &codegen.ImportSpec{
Path: path.Join(genpkg, codegen.SnakeCase(data.Service.VarName)),
Name: scope.Unique(data.Service.PkgName, "svc"),
})
apiPkg := scope.Unique(strings.ToLower(codegen.Goify(root.API.Name, false)), "api")
sections = []*codegen.SectionTemplate{codegen.Header("", apiPkg, specs)}
for _, e := range data.Endpoints {
if e.MultipartRequestDecoder != nil {
mustGen = true
sections = append(sections, &codegen.SectionTemplate{
Name: "dummy-multipart-request-decoder",
Source: dummyMultipartRequestDecoderImplT,
Data: e.MultipartRequestDecoder,
})
}
if e.MultipartRequestEncoder != nil {
mustGen = true
sections = append(sections, &codegen.SectionTemplate{
Name: "dummy-multipart-request-encoder",
Source: dummyMultipartRequestEncoderImplT,
Data: e.MultipartRequestEncoder,
})
}
}
}
if !mustGen {
return nil
}
return &codegen.File{
Path: mpath,
SectionTemplates: sections,
SkipExist: true,
}
}
const (
// input: MultipartData
dummyMultipartRequestDecoderImplT = `{{ printf "%s implements the multipart decoder for service %q endpoint %q. The decoder must populate the argument p after encoding." .FuncName .ServiceName .MethodName | comment }}
func {{ .FuncName }}(mr *multipart.Reader, p *{{ .Payload.Ref }}) error {
// Add multipart request decoder logic here
return nil
}
`
// input: MultipartData
dummyMultipartRequestEncoderImplT = `{{ printf "%s implements the multipart encoder for service %q endpoint %q." .FuncName .ServiceName .MethodName | comment }}
func {{ .FuncName }}(mw *multipart.Writer, p {{ .Payload.Ref }}) error {
// Add multipart request encoder logic here
return nil
}
`
// input: map[string]interface{}{"Services":[]*ServiceData}
httpSvrStartT = `{{ comment "handleHTTPServer starts configures and starts a HTTP server on the given URL. It shuts down the server if any error is received in the error channel." }}
func handleHTTPServer(ctx context.Context, u *url.URL{{ range $.Services }}{{ if .Service.Methods }}, {{ .Service.VarName }}Endpoints *{{ .Service.PkgName }}.Endpoints{{ end }}{{ end }}, wg *sync.WaitGroup, errc chan error, logger *log.Logger, debug bool) {
`
httpSvrLoggerT = `
// Setup goa log adapter.
var (
adapter middleware.Logger
)
{
adapter = middleware.NewLogger(logger)
}
`
httpSvrEncodingT = `
// Provide the transport specific request decoder and response encoder.
// The goa http package has built-in support for JSON, XML and gob.
// Other encodings can be used by providing the corresponding functions,
// see goa.design/encoding.
var (
dec = goahttp.RequestDecoder
enc = goahttp.ResponseEncoder
)
`
httpSvrMuxT = `
// Build the service HTTP request multiplexer and configure it to serve
// HTTP requests to the service endpoints.
var mux goahttp.Muxer
{
mux = goahttp.NewMuxer()
}
`
// input: map[string]interface{}{"APIPkg":string, "Services":[]*ServiceData}
httpSvrInitT = `
// Wrap the endpoints with the transport specific layers. The generated
// server packages contains code generated from the design which maps
// the service input and output data structures to HTTP requests and
// responses.
var (
{{- range .Services }}
{{ .Service.VarName }}Server *{{.Service.PkgName}}svr.Server
{{- end }}
)
{
eh := errorHandler(logger)
{{- if needStream .Services }}
upgrader := &websocket.Upgrader{}
{{- end }}
{{- range $svc := .Services }}
{{- if .Endpoints }}
{{ .Service.VarName }}Server = {{ .Service.PkgName }}svr.New({{ .Service.VarName }}Endpoints, mux, dec, enc, eh{{ if hasStreaming $svc }}, upgrader, nil{{ end }}{{ range .Endpoints }}{{ if .MultipartRequestDecoder }}, {{ $.APIPkg }}.{{ .MultipartRequestDecoder.FuncName }}{{ end }}{{ end }})
{{- else }}
{{ .Service.VarName }}Server = {{ .Service.PkgName }}svr.New(nil, mux, dec, enc, eh)
{{- end }}
{{- end }}
}
// Configure the mux.
{{- range .Services }}
{{ .Service.PkgName }}svr.Mount(mux{{ if .Endpoints }}, {{ .Service.VarName }}Server{{ end }})
{{- end }}
`
httpSvrMiddlewareT = `
// Wrap the multiplexer with additional middlewares. Middlewares mounted
// here apply to all the service endpoints.
var handler http.Handler = mux
{
if debug {
handler = httpmdlwr.Debug(mux, os.Stdout)(handler)
}
handler = httpmdlwr.Log(adapter)(handler)
handler = httpmdlwr.RequestID()(handler)
}
`
// input: map[string]interface{}{"Services":[]*ServiceData}
httpSvrEndT = `
// Start HTTP server using default configuration, change the code to
// configure the server as required by your service.
srv := &http.Server{Addr: u.Host, Handler: handler}
{{- range .Services }}
for _, m := range {{ .Service.VarName }}Server.Mounts {
logger.Printf("HTTP %q mounted on %s %s", m.Method, m.Verb, m.Pattern)
}
{{- end }}
(*wg).Add(1)
go func() {
defer (*wg).Done()
{{ comment "Start HTTP server in a separate goroutine." }}
go func() {
logger.Printf("HTTP server listening on %q", u.Host)
errc <- srv.ListenAndServe()
}()
<-ctx.Done()
logger.Printf("shutting down HTTP server at %q", u.Host)
{{ comment "Shutdown gracefully with a 30s timeout." }}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
srv.Shutdown(ctx)
}()
}
`
httpSvrErrorHandlerT = `
// errorHandler returns a function that writes and logs the given error.
// The function also writes and logs the error unique ID so that it's possible
// to correlate.
func errorHandler(logger *log.Logger) func(context.Context, http.ResponseWriter, error) {
return func(ctx context.Context, w http.ResponseWriter, err error) {
id := ctx.Value(middleware.RequestIDKey).(string)
w.Write([]byte("[" + id + "] encoding: " + err.Error()))
logger.Printf("[%s] ERROR: %s", id, err.Error())
}
}
`
)