| 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 // c.Written()==true. |
| 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 // Run executes the middleware chain and final handler with the given context as |
| 26 // the initial context. |
| 27 func (mc MiddlewareChain) Run(c *Context, h Handler) { |
| 28 run(c, mc, nil, h) |
| 29 } |
| 30 |
| 31 // run executes the middleware chains m and n, and the handler h using the |
| 32 // Context c as the initial context. |
| 33 func run(c *Context, m, n MiddlewareChain, h Handler) { |
| 34 switch { |
| 35 case len(m) > 0: |
| 36 m[0](c, func(ctx *Context) { |
| 37 run(ctx, m[1:], n, h) |
| 38 }) |
| 39 case len(n) > 0: |
| 40 n[0](c, func(ctx *Context) { |
| 41 run(ctx, nil, n[1:], h) |
| 42 }) |
| 43 default: |
| 44 h(c) |
| 45 } |
| 46 } |
| OLD | NEW |