| 1 | /* |
| 2 | Package pattern contains utilities for Goji Pattern authors. |
| 3 | |
| 4 | Goji users should not import this package. Instead, use the utilities provided |
| 5 | by your Pattern package. If you are looking for an implementation of Pattern, |
| 6 | try Goji's pat subpackage, which contains a simple domain specific language for |
| 7 | specifying routes. |
| 8 | |
| 9 | For Pattern authors, use of this subpackage is entirely optional. Nevertheless, |
| 10 | authors who wish to take advantage of Goji's PathPrefix optimization or who wish |
| 11 | to standardize on a few common interfaces may find this package useful. |
| 12 | */ |
| 13 | package pattern |
| 14 | |
| 15 | import ( |
| 16 | "context" |
| 17 | |
| 18 | "goji.io/internal" |
| 19 | ) |
| 20 | |
| 21 | /* |
| 22 | Variable is a standard type for the names of Pattern-bound variables, e.g. |
| 23 | variables extracted from the URL. Pass the name of a variable, cast to this |
| 24 | type, to context.Context.Value to retrieve the value bound to that name. |
| 25 | */ |
| 26 | type Variable string |
| 27 | |
| 28 | type allVariables struct{} |
| 29 | |
| 30 | /* |
| 31 | AllVariables is a standard value which, when passed to context.Context.Value, |
| 32 | returns all variable bindings present in the context, with bindings in newer |
| 33 | contexts overriding values deeper in the stack. The concrete type |
| 34 | |
| 35 | map[Variable]interface{} |
| 36 | |
| 37 | is used for this purpose. If no variables are bound, nil should be returned |
| 38 | instead of an empty map. |
| 39 | */ |
| 40 | var AllVariables = allVariables{} |
| 41 | |
| 42 | /* |
| 43 | Path returns the path that the Goji router uses to perform the PathPrefix |
| 44 | optimization. While this function does not distinguish between the absence of a |
| 45 | path and an empty path, Goji will automatically extract a path from the request |
| 46 | if none is present. |
| 47 | |
| 48 | By convention, paths are stored in their escaped form (i.e., the value returned |
| 49 | by net/url.URL.EscapedPath, and not URL.Path) to ensure that Patterns have as |
| 50 | much discretion as possible (e.g., to behave differently for '/' and '%2f'). |
| 51 | */ |
| 52 | func Path(ctx context.Context) string { |
| 53 | pi := ctx.Value(internal.Path) |
| 54 | if pi == nil { |
| 55 | return "" |
| 56 | } |
| 57 | return pi.(string) |
| 58 | } |
| 59 | |
| 60 | /* |
| 61 | SetPath returns a new context in which the given path is used by the Goji Router |
| 62 | when performing the PathPrefix optimization. See Path for more information about |
| 63 | the intended semantics of this path. |
| 64 | */ |
| 65 | func SetPath(ctx context.Context, path string) context.Context { |
| 66 | return context.WithValue(ctx, internal.Path, path) |
| 67 | } |