Chromium Code Reviews| 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 import "golang.org/x/net/context" | |
| 8 | |
| 9 // TODO(nishanths): Base and TestingBase need better names now that they are in | |
| 10 // a package named router. Previously, it was fine because they were in the | |
| 11 // middleware package. | |
| 12 | |
| 13 type ( | |
| 14 // Handler is the type for all request handlers. | |
| 15 Handler func(*Context) | |
| 16 | |
| 17 // Middleware is a function that returns a Handler. | |
| 18 Middleware func() Handler | |
|
nodir
2016/06/13 20:20:52
I think this type is unnecessary
| |
| 19 | |
| 20 // Base returns a list of handlers. It usually is | |
| 21 // the start of the middleware chain. | |
| 22 // TODO(nishanths): It may not be necessary to have a specific type for | |
|
nodir
2016/06/13 20:20:52
"//\n" before TODO
| |
| 23 // this after issue 617774. | |
| 24 Base func() []Handler | |
|
nodir
2016/06/13 20:20:52
why Base is a function that returns []Handler rath
| |
| 25 ) | |
| 26 | |
| 27 // TestingBase is Base that passes given context to the handler. Useful in | |
| 28 // tests. | |
| 29 func TestingBase(c context.Context) Base { | |
| 30 return func() (h []Handler) { | |
| 31 return []Handler{func(ctx *Context) { | |
| 32 ctx.Context = c | |
| 33 }} | |
| 34 } | |
| 35 } | |
| 36 | |
| 37 // HandlerWithContext creates a handler that assigns the given context to | |
| 38 // the Context field. | |
| 39 func HandlerWithContext(c context.Context) Handler { | |
| 40 return func(ctx *Context) { | |
| 41 ctx.Context = c | |
| 42 } | |
| 43 } | |
| 44 | |
| 45 // ChainHandlers combines handlers into a single executable function. | |
| 46 // Useful to create a single executable function for tests. | |
| 47 // The Writer, Request, and Params fields in the Context available to the | |
| 48 // handlers are not set and should be set before use. | |
| 49 func ChainHandlers(handlers ...Handler) func() { | |
| 50 return func() { | |
| 51 if len(handlers) > 0 { | |
| 52 c := &Context{handlers: handlers, index: -1} | |
| 53 c.Next() | |
| 54 } | |
| 55 } | |
| 56 } | |
| 57 | |
| 58 // HandlerWithContextValue is a middleware that adds a value to the context befo re | |
| 59 // calling the handler. | |
| 60 func HandlerWithContextValue(key, val interface{}) Handler { | |
| 61 return func(c *Context) { | |
| 62 c.Context = context.WithValue(c.Context, key, val) | |
| 63 } | |
| 64 } | |
| OLD | NEW |