forked from goadesign/goa
/
example_server.go
302 lines (282 loc) · 8.31 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
package example
import (
"os"
"path"
"path/filepath"
"strings"
"goa.design/goa/codegen"
"goa.design/goa/codegen/service"
"goa.design/goa/expr"
)
// ServerFiles returns an example server main implementation for every server
// expression in the service design.
func ServerFiles(genpkg string, root *expr.RootExpr) []*codegen.File {
var fw []*codegen.File
for _, svr := range root.API.Servers {
if m := exampleSvrMain(genpkg, root, svr); m != nil {
fw = append(fw, m)
}
}
return fw
}
// exampleSvrMain returns the default main function for the given server
// expression.
func exampleSvrMain(genpkg string, root *expr.RootExpr, svr *expr.ServerExpr) *codegen.File {
svrdata := Servers.Get(svr)
mainPath := filepath.Join("cmd", svrdata.Dir, "main.go")
if _, err := os.Stat(mainPath); !os.IsNotExist(err) {
return nil // file already exists, skip it.
}
specs := []*codegen.ImportSpec{
{Path: "context"},
{Path: "flag"},
{Path: "fmt"},
{Path: "log"},
{Path: "net/url"},
{Path: "os"},
{Path: "os/signal"},
{Path: "strings"},
{Path: "sync"},
{Path: "time"},
{Path: "goa.design/goa/middleware"},
}
// Iterate through services listed in the server expression.
svcData := make([]*service.Data, len(svr.Services))
scope := codegen.NewNameScope()
for i, svc := range svr.Services {
sd := service.Services.Get(svc)
svcData[i] = sd
specs = append(specs, &codegen.ImportSpec{
Path: path.Join(genpkg, codegen.SnakeCase(sd.VarName)),
Name: scope.Unique(sd.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})
sections := []*codegen.SectionTemplate{
codegen.Header("", "main", specs),
&codegen.SectionTemplate{
Name: "server-main-start",
Source: mainStartT,
Data: map[string]interface{}{
"Server": svrdata,
},
FuncMap: map[string]interface{}{
"join": strings.Join,
},
},
&codegen.SectionTemplate{
Name: "server-main-logger",
Source: mainLoggerT,
Data: map[string]interface{}{
"APIPkg": apiPkg,
},
},
&codegen.SectionTemplate{
Name: "server-main-services",
Source: mainSvcsT,
Data: map[string]interface{}{
"APIPkg": apiPkg,
"Services": svcData,
},
FuncMap: map[string]interface{}{
"mustInitServices": mustInitServices,
},
},
&codegen.SectionTemplate{
Name: "server-main-endpoints",
Source: mainEndpointsT,
Data: map[string]interface{}{
"Services": svcData,
},
FuncMap: map[string]interface{}{
"mustInitServices": mustInitServices,
},
},
&codegen.SectionTemplate{Name: "server-main-interrupts", Source: mainInterruptsT},
&codegen.SectionTemplate{
Name: "server-main-handler",
Source: mainServerHndlrT,
Data: map[string]interface{}{
"Server": svrdata,
"Services": svcData,
},
FuncMap: map[string]interface{}{
"goify": codegen.Goify,
"join": strings.Join,
"toUpper": strings.ToUpper,
},
},
&codegen.SectionTemplate{Name: "server-main-end", Source: mainEndT},
}
return &codegen.File{Path: mainPath, SectionTemplates: sections, SkipExist: true}
}
// mustInitServices returns true if at least one of the services defines methods.
// It is used by the template to initialize service variables.
func mustInitServices(data []*service.Data) bool {
for _, svc := range data {
if len(svc.Methods) > 0 {
return true
}
}
return false
}
const (
// input: map[string]interface{"Server": *ServerData}
mainStartT = `
func main() {
{{ comment "Define command line flags, add any other flag required to configure the service." }}
var(
hostF = flag.String("host", {{ printf "%q" .Server.DefaultHost.Name }}, "Server host (valid values: {{ (join .Server.AvailableHosts ", ") }})")
domainF = flag.String("domain", "", "Host domain name (overrides host domain specified in service design)")
{{- range .Server.Transports }}
{{ .Type }}PortF = flag.String("{{ .Type }}-port", "", "{{ .Name }} port (overrides host {{ .Name }} port specified in service design)")
{{- end }}
{{- range .Server.Variables }}
{{ .VarName }}F = flag.String({{ printf "%q" .Name }}, {{ printf "%q" .DefaultValue }}, "{{ .Description }}{{ if .Values }} (valid values: {{ join .Values ", " }}){{ end }}")
{{- end }}
secureF = flag.Bool("secure", false, "Use secure scheme (https or grpcs)")
dbgF = flag.Bool("debug", false, "Log request and response bodies")
)
flag.Parse()
`
// input: map[string]interface{"APIPkg": string}
mainLoggerT = `
{{ comment "Setup logger. Replace logger with your own log package of choice." }}
var (
logger *log.Logger
)
{
logger = log.New(os.Stderr, "[{{ .APIPkg }}] ", log.Ltime)
}
`
// input: map[string]interface{"APIPkg": string, "Services": []*service.Data}
mainSvcsT = `
{{- if mustInitServices .Services }}
{{ comment "Initialize the services." }}
var (
{{- range .Services }}
{{- if .Methods }}
{{ .VarName }}Svc {{ .PkgName }}.Service
{{- end }}
{{- end }}
)
{
{{- range .Services }}
{{- if .Methods }}
{{ .VarName }}Svc = {{ $.APIPkg }}.New{{ .StructName }}(logger)
{{- end }}
{{- end }}
}
{{- end }}
`
// input: map[string]interface{"Services": []*service.Data}
mainEndpointsT = `
{{- if mustInitServices .Services }}
{{ comment "Wrap the services in endpoints that can be invoked from other services potentially running in different processes." }}
var (
{{- range .Services }}
{{- if .Methods }}
{{ .VarName }}Endpoints *{{ .PkgName }}.Endpoints
{{- end }}
{{- end }}
)
{
{{- range .Services }}
{{- if .Methods }}
{{ .VarName }}Endpoints = {{ .PkgName }}.NewEndpoints({{ .VarName }}Svc)
{{- end }}
{{- end }}
}
{{- end }}
`
mainInterruptsT = `
// Create channel used by both the signal handler and server goroutines
// to notify the main goroutine when to stop the server.
errc := make(chan error)
// Setup interrupt handler. This optional step configures the process so
// that SIGINT and SIGTERM signals cause the services to stop gracefully.
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
errc <- fmt.Errorf("%s", <-c)
}()
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
`
// input: map[string]interface{"Server": *Data, "Services": []*service.Data}
mainServerHndlrT = `
{{ comment "Start the servers and send errors (if any) to the error channel." }}
switch *hostF {
{{- range $h := .Server.Hosts }}
case {{ printf "%q" $h.Name }}:
{{- range $u := $h.URIs }}
{{- if $.Server.HasTransport $u.Transport.Type }}
{
addr := {{ printf "%q" $u.URL }}
{{- range $h.Variables }}
{{- if .Values }}
var {{ .VarName }}Seen bool
{
for _, v := range []string{ {{ range $v := .Values }}"{{ $v }}",{{ end }} } {
if v == *{{ .VarName }}F {
{{ .VarName }}Seen = true
break
}
}
}
if !{{ .VarName }}Seen {
fmt.Fprintf(os.Stderr, "invalid value for URL '{{ .Name }}' variable: %q (valid values: {{ join .Values "," }})\n", *{{ .VarName }}F)
os.Exit(1)
}
{{- end }}
addr = strings.Replace(addr, {{ printf "\"{%s}\"" .Name }}, *{{ .VarName }}F, -1)
{{- end }}
u, err := url.Parse(addr)
if err != nil {
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", addr, err)
os.Exit(1)
}
if *secureF {
u.Scheme = "{{ $u.Transport.Type }}s"
}
if *domainF != "" {
u.Host = *domainF
}
if *{{ $u.Transport.Type }}PortF != "" {
h := strings.Split(u.Host, ":")[0]
u.Host = h + ":" + *{{ $u.Transport.Type }}PortF
} else if u.Port() == "" {
u.Host += ":{{ $u.Port }}"
}
handle{{ toUpper $u.Transport.Name }}Server(ctx, u, {{ range $.Services }}{{ if .Methods }}{{ .VarName }}Endpoints, {{ end }}{{ end }}&wg, errc, logger, *dbgF)
}
{{- end }}
{{ end }}
{{- end }}
default:
fmt.Fprintf(os.Stderr, "invalid host argument: %q (valid hosts: {{ join .Server.AvailableHosts "|" }})\n", *hostF)
}
`
mainEndT = `
{{ comment "Wait for signal." }}
logger.Printf("exiting (%v)", <-errc)
{{ comment "Send cancellation signal to the goroutines." }}
cancel()
wg.Wait()
logger.Println("exited")
}
`
)