Chromium Code Reviews| Index: server/router/handler.go |
| diff --git a/server/router/handler.go b/server/router/handler.go |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..c15f8b6b3e6c048f05bfe51d10d69fb7c5637d8b |
| --- /dev/null |
| +++ b/server/router/handler.go |
| @@ -0,0 +1,45 @@ |
| +// Copyright 2016 The LUCI Authors. All rights reserved. |
| +// Use of this source code is governed under the Apache License, Version 2.0 |
| +// that can be found in the LICENSE file. |
| + |
| +package router |
| + |
| +// Handler is the type for all request handlers. |
| +type Handler func(*Context) |
| + |
| +// Middleware is a function that accepts a shared context and the next |
| +// function. Since Middleware is typically part of a chain of functions |
| +// that handles an HTTP request, it must obey the following rules. |
| +// |
| +// - Middleware must call next if it has not written to the Context |
| +// by the end of the function. |
| +// - Middleware must not call next if it has written to the Context. |
| +// - Middleware must not write to the Context after next is called and |
| +// the Context has been written to. |
| +// - Middleware may modify the embedded context before calling next. |
| +type Middleware func(c *Context, next Handler) |
| + |
| +// MiddlewareChain is a list of Middleware. |
| +type MiddlewareChain []Middleware |
| + |
| +// VoidMiddleware is middleware that simply calls next with the context. |
| +var VoidMiddleware = func(c *Context, next Handler) { |
|
Vadim Sh.
2016/06/18 16:57:20
what do you think about teaching 'run' to recogniz
nishanths
2016/06/19 02:47:02
Good idea; not too surprising to users either. Don
|
| + next(c) |
| +} |
| + |
| +// run executes the middleware chains m and n, and the handler h using the |
| +// Context c as the initial context. |
| +func run(c *Context, m, n MiddlewareChain, h Handler) { |
| + switch { |
| + case len(m) > 0: |
| + m[0](c, func(ctx *Context) { |
| + run(ctx, m[1:], n, h) |
| + }) |
| + case len(n) > 0: |
| + n[0](c, func(ctx *Context) { |
| + run(ctx, nil, n[1:], h) |
| + }) |
| + default: |
| + h(c) |
| + } |
| +} |