trout
2016-01-21
Parent:3df515f0cec5
trout/route.go
Add Router prefix. Make the Router use a prefix that will be stripped before matching URLs against Endpoints, so we can ignore the prefix that http.Handle is matching against, instead of duplicating it, which can lead to confusing 404s.
1 package trout
3 import (
4 "net/http"
5 "strconv"
6 "strings"
7 "time"
8 )
10 var (
11 default404Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12 w.WriteHeader(http.StatusNotFound)
13 w.Write([]byte("404 Not Found"))
14 return
15 }))
16 default405Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17 w.Header().Set("Allow", strings.Join(r.Header[http.CanonicalHeaderKey("Trout-Methods")], ", "))
18 w.WriteHeader(http.StatusMethodNotAllowed)
19 w.Write([]byte("405 Method Not Allowed"))
20 return
21 }))
22 )
24 // RequestVars returns easy-to-access mappings of parameters to values for URL templates. Any {parameter} in
25 // your URL template will be available in the returned Header as a slice of strings, one for each instance of
26 // the {parameter}. In the case of a parameter name being used more than once in the same URL template, the
27 // values will be in the slice in the order they appeared in the template.
28 //
29 // Values can easily be accessed by using the .Get() method of the returned Header, though to access multiple
30 // values, they must be accessed through the map. All parameters use http.CanonicalHeaderKey for their formatting.
31 // When using .Get(), the parameter name will be transformed automatically. When utilising the Header as a map,
32 // the parameter name needs to have http.CanonicalHeaderKey applied manually.
33 func RequestVars(r *http.Request) http.Header {
34 res := http.Header{}
35 for h, v := range r.Header {
36 stripped := strings.TrimPrefix(h, http.CanonicalHeaderKey("Trout-Param-"))
37 if stripped != h {
38 res[stripped] = v
39 }
40 }
41 return res
42 }
44 // Router defines a set of Endpoints that map requests to the http.Handlers. The http.Handler assigned to
45 // Handle404, if set, will be called when no Endpoint matches the current request. The http.Handler assigned
46 // to Handle405, if set, will be called when an Endpoint matches the current request, but has no http.Handler
47 // set for the HTTP method that the request used. Should either of these properties be unset, a default
48 // http.Handler will be used.
49 //
50 // The Router type is safe for use with empty values, but makes no attempt at concurrency-safety in adding
51 // Endpoints or in setting properties. It should also be noted that the adding Endpoints while simultaneously
52 // routing requests will lead to undefined and (almost certainly) undesirable behaviour. Routers are intended
53 // to be initialised with a set of Endpoints, and then start serving requests. Using them outside of this use
54 // case is unsupported.
55 type Router struct {
56 t *trie
57 Handle404 http.Handler
58 Handle405 http.Handler
59 prefix string
60 }
62 func (router *Router) serve404(w http.ResponseWriter, r *http.Request, t time.Time) {
63 h := default404Handler
64 if router.Handle404 != nil {
65 h = router.Handle404
66 }
67 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10))
68 h.ServeHTTP(w, r)
69 }
71 func (router *Router) serve405(w http.ResponseWriter, r *http.Request, t time.Time) {
72 h := default405Handler
73 if router.Handle405 != nil {
74 h = router.Handle405
75 }
76 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10))
77 h.ServeHTTP(w, r)
78 }
80 func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 start := time.Now()
82 if router.t == nil {
83 router.serve404(w, r, start)
84 return
85 }
86 u := strings.TrimPrefix(r.URL.Path, router.prefix)
87 pieces := strings.Split(strings.ToLower(strings.Trim(u, "/")), "/")
88 router.t.RLock()
89 defer router.t.RUnlock()
90 branches := make([]*branch, len(pieces))
91 path, ok := router.t.match(pieces)
92 if !ok {
93 router.serve404(w, r, start)
94 return
95 }
96 b := router.t.branch
97 for i, pos := range path {
98 b = b.children[pos]
99 branches[i] = b
100 }
101 v := vars(branches, pieces)
102 for key, vals := range v {
103 r.Header[http.CanonicalHeaderKey("Trout-Param-"+key)] = vals
104 }
105 ms := make([]string, len(b.methods))
106 i := 0
107 for m := range b.methods {
108 ms[i] = m
109 i = i + 1
110 }
111 r.Header[http.CanonicalHeaderKey("Trout-Methods")] = ms
112 h := b.methods[r.Method]
113 if h == nil {
114 router.serve405(w, r, start)
115 return
116 }
117 r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(start).Nanoseconds(), 10))
118 h.ServeHTTP(w, r)
119 }
121 // SetPrefix sets a string prefix for the Router that won't be taken into account when matching Endpoints.
122 // This is usually set to whatever path is associated with the http.Handler serving the Router.
123 func (router *Router) SetPrefix(prefix string) {
124 router.prefix = prefix
125 }
127 // Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces
128 // to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id`
129 // that should be filled with whatever the request has in that space.
130 //
131 // Parameters are always `/`-separated strings. There is no support for regular expressions or other limitations
132 // on what may be in those strings. A parameter is simply defined as "whatever is between these two / characters".
133 func (router *Router) Endpoint(e string) *Endpoint {
134 e = strings.Trim(e, "/")
135 e = strings.ToLower(e)
136 pieces := strings.Split(e, "/")
137 if router.t == nil {
138 router.t = &trie{}
139 }
140 router.t.Lock()
141 defer router.t.Unlock()
142 if router.t.branch == nil {
143 router.t.branch = &branch{
144 parent: nil,
145 children: []*branch{},
146 key: "",
147 isParam: false,
148 methods: map[string]http.Handler{},
149 }
150 }
151 closest := findClosestLeaf(pieces, router.t.branch)
152 b := router.t.branch
153 for _, pos := range closest {
154 b = b.children[pos]
155 }
156 if len(closest) == len(pieces) {
157 return (*Endpoint)(b)
158 }
159 offset := len(closest)
160 for i := offset; i < len(pieces); i++ {
161 piece := pieces[i]
162 var isParam bool
163 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" {
164 isParam = true
165 piece = piece[1 : len(piece)-1]
166 }
167 b = b.addChild(piece, isParam)
168 }
169 return (*Endpoint)(b)
170 }
172 func vars(path []*branch, pieces []string) map[string][]string {
173 v := map[string][]string{}
174 for pos, p := range path {
175 if !p.isParam {
176 continue
177 }
178 _, ok := v[p.key]
179 if !ok {
180 v[p.key] = []string{pieces[pos]}
181 continue
182 }
183 v[p.key] = append(v[p.key], pieces[pos])
184 }
185 return v
186 }
188 func findClosestLeaf(pieces []string, b *branch) []int {
189 offset := 0
190 path := []int{}
191 longest := []int{}
192 num := len(pieces)
193 for i := 0; i < num; i++ {
194 piece := pieces[i]
195 var isParam bool
196 if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" {
197 isParam = true
198 piece = piece[1 : len(piece)-1]
199 }
200 offset = pickNextRoute(b, offset, piece, isParam)
201 if offset == -1 {
202 if len(path) == 0 {
203 // exhausted our options, bail
204 break
205 }
206 // no match, maybe save this and backup
207 if len(path) > len(longest) {
208 longest = append([]int{}, path...) // copy them over so they don't get modified
209 }
210 path, offset = backup(path)
211 offset = offset + 1
212 b = b.parent
213 i = i - 2
214 } else {
215 path = append(path, offset)
216 b = b.children[offset]
217 offset = 0
218 }
219 }
220 if len(longest) < len(path) {
221 longest = append([]int{}, path...)
222 }
223 return longest
224 }
226 func pickNextRoute(b *branch, offset int, input string, variable bool) int {
227 count := len(b.children)
228 for i := offset; i < count; i++ {
229 if b.children[i].key == input && b.children[i].isParam == variable {
230 return i
231 }
232 }
233 return -1
234 }
236 // Endpoint defines a single URL template that requests can be matched against. It uses
237 // URL parameters to accept variables in the URL structure and make them available to
238 // the Handlers associated with the Endpoint.
239 type Endpoint branch
241 // Handler associates the passed http.Handler with the Endpoint. This http.Handler will be
242 // used for all requests, regardless of the HTTP method they are using, unless overridden by
243 // the Methods method. Endpoints without a http.Handler associated with them will not be
244 // considered matches for requests, unless the request was made using an HTTP method that the
245 // Endpoint has an http.Handler mapped to.
246 func (e *Endpoint) Handler(h http.Handler) {
247 (*branch)(e).setHandler("", h)
248 }
250 // Methods simple returns a Methods object that will enable the mapping of the passed HTTP
251 // request methods to a Methods object. On its own, this function does not modify anything. It
252 // should, instead, be used as a friendly shorthand to get to the Methods.Handler method.
253 func (e *Endpoint) Methods(m ...string) Methods {
254 return Methods{
255 e: e,
256 m: m,
257 }
258 }
260 // Methods defines a pairing of an Endpoint to the HTTP request methods that should be mapped to
261 // specific http.Handlers. Its sole purpose is to enable the Methods.Handler method.
262 type Methods struct {
263 e *Endpoint
264 m []string
265 }
267 // Handler maps a Methods object to a specific http.Handler. This overrides the http.Handler
268 // associated with the Endpoint to only handle specific HTTP method(s).
269 func (m Methods) Handler(h http.Handler) {
270 b := (*branch)(m.e)
271 for _, method := range m.m {
272 b.setHandler(method, h)
273 }
274 }