| OLD | NEW |
| (Empty) | |
| 1 // Copyright 2016 The LUCI Authors. All rights reserved. |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 |
| 3 // that can be found in the LICENSE file. |
| 4 |
| 5 package router |
| 6 |
| 7 // Handler is the type for all request handlers. |
| 8 type Handler func(*Context) |
| 9 |
| 10 // Middleware is a function that accepts a shared context and the next |
| 11 // function. Since Middleware is typically part of a chain of functions |
| 12 // that handles an HTTP request, it must obey the following rules. |
| 13 // |
| 14 // - Middleware must call next if it has not written to the Context |
| 15 // by the end of the function. |
| 16 // - Middleware must not call next if it has written to the Context. |
| 17 // - Middleware must not write to the Context after next is called and |
| 18 // the Context has been written to. |
| 19 // - Middleware may modify the embedded context before calling next. |
| 20 type Middleware func(c *Context, next Handler) |
| 21 |
| 22 // MiddlewareChain is a list of Middleware. |
| 23 type MiddlewareChain []Middleware |
| 24 |
| 25 // RunMiddleware executes the middleware chain and handlers with the given |
| 26 // initial context. Useful to execute a chain of functions in tests. |
| 27 func RunMiddleware(c *Context, m MiddlewareChain, h Handler) { |
| 28 run(c, m, nil, h) |
| 29 } |
| 30 |
| 31 // run executes the middleware chains m and n and the handler h using |
| 32 // c as the initial context. If a middleware or handler is nil, run |
| 33 // simply advances to the next middleware or handler. |
| 34 func run(c *Context, m, n MiddlewareChain, h Handler) { |
| 35 switch { |
| 36 case len(m) > 0: |
| 37 if m[0] != nil { |
| 38 m[0](c, func(ctx *Context) { run(ctx, m[1:], n, h) }) |
| 39 } else { |
| 40 run(c, m[1:], n, h) |
| 41 } |
| 42 case len(n) > 0: |
| 43 if n[0] != nil { |
| 44 n[0](c, func(ctx *Context) { run(ctx, nil, n[1:], h) }) |
| 45 } else { |
| 46 run(c, nil, n[1:], h) |
| 47 } |
| 48 case h != nil: |
| 49 h(c) |
| 50 } |
| 51 } |
| OLD | NEW |