forked from goadesign/goa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
303 lines (274 loc) · 11 KB
/
service.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
package goa
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"golang.org/x/net/context"
)
type (
// Service is the data structure supporting goa services.
// It provides methods for configuring a service and running it.
// At the basic level a service consists of a set of controllers, each implementing a given
// resource actions. goagen generates global functions - one per resource - that make it
// possible to mount the corresponding controller onto a service. A service contains the
// middleware, error handler, encoders and muxes shared by all its controllers. Setting up
// a service might look like:
//
// service := goa.New("my api")
// service.Use(SomeMiddleware())
// rc := NewResourceController()
// rc.Use(SomeOtherMiddleware())
// service.MountResourceController(service, rc)
// service.ListenAndServe(":80")
//
// where NewResourceController returns an object that implements the resource actions as
// defined by the corresponding interface generated by goagen.
Service struct {
*ServiceVersion // Embedded default version
Name string // Service name
ErrorHandler ErrorHandler // Service error handler
Middleware []Middleware // Middleware chain
versions map[string]*ServiceVersion // Versions by version string
}
// ServiceVersion represents a service version, identified by a version name. This is where
// Service data that needs to be different per version lives.
ServiceVersion struct {
VersionName string // VersionName is the version string
Mux ServeMux // Mux is the version request mux
decoderPools map[string]*decoderPool // Registered decoders for the service
encoderPools map[string]*encoderPool // Registered encoders for the service
encodableContentTypes []string // List of contentTypes for response negotiation
}
// Controller provides the common state and behavior for generated controllers.
Controller struct {
Name string // Controller resource name
Service *Service // Service which exposes controller
ErrorHandler ErrorHandler // Controller specific error handler if any
Middleware []Middleware // Controller specific middleware if any
}
// Handler defines the controller handler signatures.
// If a controller handler returns an error then the service error handler is invoked
// with the request context and the error. The error handler is responsible for writing the
// HTTP response. See DefaultErrorHandler and TerseErrorHandler.
Handler func(context.Context, http.ResponseWriter, *http.Request) error
// ErrorHandler defines the service error handler signature.
ErrorHandler func(context.Context, http.ResponseWriter, *http.Request, error)
// Unmarshaler defines the request payload unmarshaler signatures.
Unmarshaler func(context.Context, *http.Request) error
// DecodeFunc is the function that initialize the unmarshaled payload from the request body.
DecodeFunc func(context.Context, io.ReadCloser, interface{}) error
)
// New instantiates an service with the given name and default decoders/encoders.
func New(name string) *Service {
service := &Service{
Name: name,
ErrorHandler: DefaultErrorHandler,
}
service.ServiceVersion = &ServiceVersion{
Mux: NewMux(service),
decoderPools: map[string]*decoderPool{},
encoderPools: map[string]*encoderPool{},
encodableContentTypes: []string{},
}
return service
}
// Use adds a middleware to the service wide middleware chain.
// See NewMiddleware for wrapping goa and http handlers into goa middleware.
// goa comes with a set of commonly used middleware, see middleware.go.
// Controller specific middleware should be mounted using the Controller type Use method instead.
func (service *Service) Use(m Middleware) {
service.Middleware = append(service.Middleware, m)
}
// ListenAndServe starts a HTTP server and sets up a listener on the given host/port.
func (service *Service) ListenAndServe(addr string) error {
Info(RootContext, "listen", KV{"address", addr})
return http.ListenAndServe(addr, service.Mux)
}
// ListenAndServeTLS starts a HTTPS server and sets up a listener on the given host/port.
func (service *Service) ListenAndServeTLS(addr, certFile, keyFile string) error {
Info(RootContext, "listen ssl", KV{"address", addr})
return http.ListenAndServeTLS(addr, certFile, keyFile, service.Mux)
}
// ServeFiles replies to the request with the contents of the named file or directory. The logic
// for what to do when the filename points to a file vs. a directory is the same as the standard
// http package ServeFile function. The path may end with a wildcard that matches the rest of the
// URL (e.g. *filepath). If it does the matching path is appended to filename to form the full file
// path, so:
// ServeFiles("/index.html", "/www/data/index.html")
// Returns the content of the file "/www/data/index.html" when requests are sent to "/index.html"
// and:
// ServeFiles("/assets/*filepath", "/www/data/assets")
// returns the content of the file "/www/data/assets/x/y/z" when requests are sent to
// "/assets/x/y/z".
func (service *Service) ServeFiles(path, filename string) error {
if strings.Contains(path, ":") {
return fmt.Errorf("path may only include wildcards that match the entire end of the URL (e.g. *filepath)")
}
if _, err := os.Stat(filename); err != nil {
return fmt.Errorf("ServeFiles: %s", err)
}
rel := filename
if wd, err := os.Getwd(); err == nil {
if abs, err := filepath.Abs(filename); err == nil {
if r, err := filepath.Rel(wd, abs); err == nil {
rel = r
}
}
}
Info(RootContext, "mount file", KV{"filename", rel}, KV{"path", fmt.Sprintf("GET %s", path)})
ctrl := service.NewController("FileServer")
var wc string
if idx := strings.Index(path, "*"); idx > -1 && idx < len(path)-1 {
wc = path[idx+1:]
}
handle := ctrl.MuxHandler("Serve", func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
fullpath := filename
r := Request(ctx)
if len(wc) > 0 {
if m, ok := r.Params[wc]; ok {
fullpath = filepath.Join(fullpath, m[0])
}
}
Info(RootContext, "serve", KV{"path", r.URL.Path}, KV{"filename", fullpath})
http.ServeFile(Response(ctx), r.Request, fullpath)
return nil
}, nil)
service.Mux.Handle("GET", path, handle)
return nil
}
// Version instantiates a new - or returns the existing - ServiceVersion based on the version name.
func (service *Service) Version(name string) *ServiceVersion {
if service.versions == nil {
service.versions = make(map[string]*ServiceVersion, 1)
}
ver, ok := service.versions[name]
if ok {
return ver
}
var verMux ServeMux
if m, ok := service.Mux.(VersionMux); ok {
verMux = m.Mux(name)
} else {
verMux = service.Mux
}
ver = &ServiceVersion{
VersionName: name,
Mux: verMux,
decoderPools: map[string]*decoderPool{},
encoderPools: map[string]*encoderPool{},
encodableContentTypes: []string{},
}
service.versions[ver.VersionName] = ver
return ver
}
// NewController returns a controller for the given resource. This method is mainly intended for
// use by the generated code. User code shouldn't have to call it directly.
func (service *Service) NewController(resName string) *Controller {
return &Controller{
Name: resName,
Service: service,
}
}
// Use adds a middleware to the controller.
// See NewMiddleware for wrapping goa and http handlers into goa middleware.
// goa comes with a set of commonly used middleware, see middleware.go.
func (ctrl *Controller) Use(m Middleware) {
ctrl.Middleware = append(ctrl.Middleware, m)
}
// MiddlewareChain returns the set of middleware that must be applied to requests sent to the
// controller.
func (ctrl *Controller) MiddlewareChain() []Middleware {
return append(ctrl.Service.Middleware, ctrl.Middleware...)
}
// HandleError invokes the controller error handler or - if there isn't one - the service error
// handler.
func (ctrl *Controller) HandleError(ctx context.Context, rw http.ResponseWriter, req *http.Request, err error) {
status := 500
if _, ok := err.(*BadRequestError); ok {
status = 400
}
go IncrCounter([]string{"goa", "handler", "error", strconv.Itoa(status)}, 1.0)
if ctrl.ErrorHandler != nil {
ctrl.ErrorHandler(ctx, rw, req, err)
} else if ctrl.Service.ErrorHandler != nil {
ctrl.Service.ErrorHandler(ctx, rw, req, err)
}
}
// MuxHandler wraps a request handler into a MuxHandler. The MuxHandler initializes the
// request context by loading the request state, invokes the handler and in case of error invokes
// the controller (if there is one) or Service error handler.
// This function is intended for the controller generated code. User code should not need to call
// it directly.
func (ctrl *Controller) MuxHandler(name string, hdlr Handler, unm Unmarshaler) MuxHandler {
// Setup middleware outside of closure
middleware := func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
if !Response(ctx).Written() {
if err := hdlr(ctx, rw, req); err != nil {
ctrl.HandleError(ctx, rw, req, err)
}
}
return nil
}
chain := ctrl.MiddlewareChain()
ml := len(chain)
for i := range chain {
middleware = chain[ml-i-1](middleware)
}
return func(rw http.ResponseWriter, req *http.Request, params url.Values) {
// Build context
ctx := NewLogContext(RootContext,
KV{"service", ctrl.Service.Name}, KV{"ctrl", ctrl.Name}, KV{"action", name})
ctx = NewContext(ctx, ctrl.Service, rw, req, params)
// Load body if any
var err error
if req.ContentLength > 0 && unm != nil {
err = unm(ctx, req)
}
// Handle invalid payload
handler := middleware
if err != nil {
handler = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
msg := "invalid encoding: " + err.Error()
rw.Header().Set("Content-Type", "Service/json")
rw.WriteHeader(400)
rw.Write([]byte(fmt.Sprintf(`{"kind":"invalid request","msg":%q}`, msg)))
return nil
}
for i := range chain {
handler = chain[ml-i-1](handler)
}
}
// Invoke middleware chain, wrap writer to capture response status and length
handler(ctx, Response(ctx), req)
}
}
// DefaultErrorHandler returns a 400 response for request validation errors (instances of
// BadRequestError) and a 500 response for other errors. It writes the error message to the
// response body in both cases.
func DefaultErrorHandler(ctx context.Context, rw http.ResponseWriter, req *http.Request, e error) {
status := 500
if _, ok := e.(*BadRequestError); ok {
status = 400
} else {
Log.Error(ctx, e.Error())
}
Response(ctx).Send(ctx, status, e.Error())
}
// TerseErrorHandler behaves like DefaultErrorHandler except that it does not write to the response
// body for internal errors.
func TerseErrorHandler(ctx context.Context, rw http.ResponseWriter, req *http.Request, e error) {
status := 500
var body interface{}
if _, ok := e.(*BadRequestError); ok {
status = 400
body = e.Error()
} else {
Log.Error(ctx, e.Error())
}
Response(ctx).Send(ctx, status, body)
}