Repository navigation
Expand file tree
/
Copy pathservice.go
More file actions
368 lines (326 loc) · 13.7 KB
/
Copy pathservice.go
File metadata and controls
368 lines (326 loc) · 13.7 KB
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
package goa
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/julienschmidt/httprouter"
"golang.org/x/net/context"
log "gopkg.in/inconshreveable/log15.v2"
)
type (
// Service is the interface implemented by all goa services.
// It provides methods for configuring a service and running it.
Service interface {
// Logging methods, configure the log handler using the Logger global variable.
log.Logger
// Name is the name of the goa application.
Name() string
// ErrorHandler returns the currently set error handler, useful for middleware.
ErrorHandler() ErrorHandler
// SetErrorHandler allows setting the service-wide error handler.
SetErrorHandler(ErrorHandler)
// Use adds a middleware to the service-wide middleware chain.
Use(m Middleware)
// ListenAndServe starts a HTTP server on the given port.
ListenAndServe(addr string) error
// ListenAndServeTLS starts a HTTPS server on the given port.
ListenAndServeTLS(add, certFile, keyFile string) error
// ServeFiles serves files from the given file system root.
// The path must end with "/*filepath", files are then served from the local
// path /defined/root/dir/*filepath.
// For example if root is "/etc" and *filepath is "passwd", the local file
// "/etc/passwd" would be served.
// Internally a http.FileServer is used, therefore http.NotFound is used instead
// of the service's NotFound handler.
// To use the operating system's file system implementation,
// use http.Dir:
// service.ServeFiles("/src/*filepath", http.Dir("/var/www"))
ServeFiles(path string, root http.FileSystem)
// HTTPHandler returns a http.Handler interface to the underlying service.
// Note: using the handler directly bypasses the graceful shutdown behavior of
// services instantiated with NewGraceful.
HTTPHandler() http.Handler
// NewController returns a controller for the resource with the given name.
// This method is mainly intended for use by generated code.
NewController(resName string) Controller
}
// Controller is the interface implemented by all goa controllers.
// A controller implements a given resource actions. There is a one-to-one relationship
// between designed resources and generated controllers.
// Controllers may override the service wide error handler and be equipped with controller
// specific middleware.
Controller interface {
// Use adds a middleware to the controller middleware chain.
// It is a convenient method for doing append(ctrl.MiddlewareChain(), m)
Use(Middleware)
// MiddlewareChain returns the controller middleware chain including the
// service-wide middleware.
MiddlewareChain() []Middleware
// ErrorHandler returns the currently set error handler.
ErrorHandler() ErrorHandler
// SetErrorHandler sets the controller specific error handler.
SetErrorHandler(ErrorHandler)
// NewHTTPRouterHandle returns a httprouter handle from a goa handler.
// This function is intended for the controller generated code.
// User code should not need to call it directly.
NewHTTPRouterHandle(actName string, h Handler) httprouter.Handle
}
// Application represents a goa application. At the basic level an application 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 an application. An application contains the middleware, logger and error
// handler shared by all its controllers. Setting up an application might look like:
//
// api := goa.New("my api")
// api.Use(SomeMiddleware())
// rc := NewResourceController()
// rc.Use(SomeOtherMiddleware())
// app.MountResourceController(api, rc)
// api.ListenAndServe(":80")
//
// where NewResourceController returns an object that implements the resource actions as
// defined by the corresponding interface generated by goagen.
Application struct {
log.Logger // Application logger
name string // Application name
errorHandler ErrorHandler // Application error handler
middleware []Middleware // Middleware chain
Router *httprouter.Router // Application router
}
// ApplicationController provides the common state and behavior for generated controllers.
ApplicationController struct {
log.Logger // Controller logger
app *Application //Application which exposes controller
errorHandler ErrorHandler // Controller specific error handler if any
middleware []Middleware // Controller specific middleware if any
}
// Handler defines the controller handler signatures.
// Controller handlers accept a context and return an error.
// The context provides typed access to the request and response state. It implements
// the golang.org/x/net/context package Context interface so that handlers may define
// deadlines and cancelation signals - see the Timeout middleware as an example.
// If a controller handler returns an error then the application 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) error
// ErrorHandler defines the application error handler signature.
ErrorHandler func(*Context, error)
)
var (
// Log is the global logger from which other loggers (e.g. request specific loggers) are
// derived. Configure it by setting its handler prior to calling New.
// See https://godoc.org/github.com/inconshreveable/log15
Log log.Logger
// RootContext is the root context from which all request contexts are derived.
// Set values in the root context prior to starting the server to make these values
// available to all request handlers:
//
// goa.RootContext = goa.RootContext.WithValue(key, value)
//
RootContext context.Context
// cancel is the root context CancelFunc.
// Call Cancel to send a cancellation signal to all the active request handlers.
cancel context.CancelFunc
)
// Log to STDOUT by default.
func init() {
Log = log.New()
Log.SetHandler(log.StdoutHandler)
RootContext, cancel = context.WithCancel(context.Background())
}
// New instantiates an application with the given name.
func New(name string) Service {
return &Application{
Logger: Log.New("app", name),
name: name,
errorHandler: DefaultErrorHandler,
Router: httprouter.New(),
}
}
// Cancel sends a cancellation signal to all handlers through the action context.
// see https://godoc.org/golang.org/x/net/context for details on how to handle the signal.
func Cancel() {
cancel()
}
// Name returns the application name.
func (app *Application) Name() string {
return app.name
}
// Use adds a middleware to the application 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 (app *Application) Use(m Middleware) {
app.middleware = append(app.middleware, m)
}
// ErrorHandler returns the currently set error handler.
func (app *Application) ErrorHandler() ErrorHandler {
return app.errorHandler
}
// SetErrorHandler defines an application wide error handler.
// The default error handler (DefaultErrorHandler) responds with a 500 status code and the error
// message in the response body.
// TerseErrorHandler provides an alternative implementation that does not write the error message
// to the response body for internal errors (e.g. for production).
// Set it with SetErrorHandler(TerseErrorHandler).
// Controller specific error handlers should be set using the Controller type SetErrorHandler
// method instead.
func (app *Application) SetErrorHandler(handler ErrorHandler) {
app.errorHandler = handler
}
// ListenAndServe starts a HTTP server and sets up a listener on the given host/port.
func (app *Application) ListenAndServe(addr string) error {
app.Info("listen", "addr", addr)
return http.ListenAndServe(addr, app.Router)
}
// ListenAndServeTLS starts a HTTPS server and sets up a listener on the given host/port.
func (app *Application) ListenAndServeTLS(addr, certFile, keyFile string) error {
app.Info("listen ssl", "addr", addr)
return http.ListenAndServeTLS(addr, certFile, keyFile, app.Router)
}
// ServeFiles simply delegates to the underlying router.
func (app *Application) ServeFiles(path string, root http.FileSystem) {
app.HTTPHandler().(*httprouter.Router).ServeFiles(path, root)
}
// HTTPHandler returns a http.Handler to the service.
func (app *Application) HTTPHandler() http.Handler {
return app.Router
}
// 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 (app *Application) NewController(resName string) Controller {
logger := app.New("ctrl", resName)
return &ApplicationController{
Logger: logger,
app: app,
}
}
// 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 *ApplicationController) Use(m Middleware) {
ctrl.middleware = append(ctrl.middleware, m)
}
// MiddlewareChain returns the controller middleware chain.
func (ctrl *ApplicationController) MiddlewareChain() []Middleware {
return append(ctrl.app.middleware, ctrl.middleware...)
}
// ErrorHandler returns the currently set error handler.
func (ctrl *ApplicationController) ErrorHandler() ErrorHandler {
return ctrl.errorHandler
}
// SetErrorHandler defines a controller specific error handler. When a controller action returns an
// error goa checks whether the controller is equipped with a error handler and if so calls it with
// the error given as argument. If there is no controller error handler then goa calls the
// application wide error handler instead.
func (ctrl *ApplicationController) SetErrorHandler(handler ErrorHandler) {
ctrl.errorHandler = handler
}
// HandleError invokes the controller error handler or - if there isn't one - the service error
// handler.
func (ctrl *ApplicationController) HandleError(ctx *Context, err error) {
if ctrl.errorHandler != nil {
ctrl.errorHandler(ctx, err)
} else if ctrl.app.errorHandler != nil {
ctrl.app.errorHandler(ctx, err)
}
}
// NewHTTPRouterHandle returns a httprouter handle from a goa handler. This handle 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 application error handler.
// This function is intended for the controller generated code. User code should not need to call
// it directly.
func (ctrl *ApplicationController) NewHTTPRouterHandle(actName string, h Handler) httprouter.Handle {
// Setup middleware outside of closure
chain := ctrl.MiddlewareChain()
ml := len(chain)
middleware := func(ctx *Context) error {
if !ctx.ResponseWritten() {
if err := h(ctx); err != nil {
ctrl.HandleError(ctx, err)
}
}
return nil
}
for i := range chain {
middleware = chain[ml-i-1](middleware)
}
logger := ctrl.New("action", actName)
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Collect URL and query string parameters
params := make(map[string]string, len(p))
for _, param := range p {
params[param.Key] = param.Value
}
q := r.URL.Query()
query := make(map[string][]string, len(q))
for name, value := range q {
query[name] = value
}
// Load body if any
var payload interface{}
var err error
if r.ContentLength > 0 {
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&payload)
}
// Build context
gctx, cancel := context.WithCancel(RootContext)
defer cancel() // Signal completion of request to any child goroutine
ctx := NewContext(gctx, r, w, params, query, payload)
ctx.Logger = logger
// Handle invalid payload
handler := middleware
if err != nil {
handler = func(ctx *Context) error {
ctx.Respond(400, []byte(fmt.Sprintf(`{"kind":"invalid request","msg":"invalid JSON: %s"}`, err)))
return nil
}
for i := range chain {
handler = chain[ml-i-1](handler)
}
}
// Invoke middleware chain
handler(ctx)
// Make sure a response is sent back to client.
if ctx.ResponseStatus() == 0 {
ctrl.HandleError(ctx, fmt.Errorf("unhandled request"))
}
}
}
// 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(c *Context, e error) {
status := 500
if _, ok := e.(*BadRequestError); ok {
c.Header().Set("Content-Type", "application/json")
status = 400
}
if err := c.Respond(status, []byte(e.Error())); err != nil {
Log.Error("failed to send default error handler response", "err", err)
}
}
// TerseErrorHandler behaves like DefaultErrorHandler except that it does not set the response
// body for internal errors.
func TerseErrorHandler(c *Context, e error) {
status := 500
var body []byte
if _, ok := e.(*BadRequestError); ok {
c.Header().Set("Content-Type", "application/json")
status = 400
body = []byte(e.Error())
}
if err := c.Respond(status, body); err != nil {
Log.Error("failed to send terse error handler response", "err", err)
}
}
// Fatal logs a critical message and exits the process with status code 1.
// This function is meant to be used by initialization code to prevent the application from even
// starting up when something is obviously wrong.
// In particular this function should probably not be used when serving requests.
func Fatal(msg string, ctx ...interface{}) {
log.Crit(msg, ctx...)
os.Exit(1)
}