trout
2015-03-16
Child:bf38b050b6c4
trout/route.go
First pass at a router library. First pass at a router library and, incidentally, implementing a trie. I could probably optimise the search for the right branch somehow, but I honestly just can't be bothered right now. I also haven't tested this at all or even tried to run it, so who knows if my code even works. But it compiles, go vet and golint have found nothing to complain about, it has documentation, and it's properly formatted. So it's already better than most software out there. </ba dump tiss>
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/route.go Mon Mar 16 00:10:38 2015 -0400 1.3 @@ -0,0 +1,259 @@ 1.4 +package trout 1.5 + 1.6 +import ( 1.7 + "net/http" 1.8 + "strconv" 1.9 + "strings" 1.10 + "time" 1.11 +) 1.12 + 1.13 +var ( 1.14 + default404Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 1.15 + w.WriteHeader(http.StatusNotFound) 1.16 + w.Write([]byte("404 Not Found")) 1.17 + return 1.18 + })) 1.19 + default405Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 1.20 + w.WriteHeader(http.StatusMethodNotAllowed) 1.21 + w.Write([]byte("405 Method Not Allowed")) 1.22 + return 1.23 + })) 1.24 +) 1.25 + 1.26 +// RequestVars returns easy-to-access mappings of parameters to values for URL templates. Any {parameter} in 1.27 +// your URL template will be available in the returned Header as a slice of strings, one for each instance of 1.28 +// the {parameter}. In the case of a parameter name being used more than once in the same URL template, the 1.29 +// values will be in the slice in the order they appeared in the template. 1.30 +// 1.31 +// Values can easily be accessed by using the .Get() method of the returned Header, though to access multiple 1.32 +// values, they must be accessed through the map. All parameters use http.CanonicalHeaderKey for their formatting. 1.33 +// When using .Get(), the parameter name will be transformed automatically. When utilising the Header as a map, 1.34 +// the parameter name needs to have http.CanonicalHeaderKey applied manually. 1.35 +func RequestVars(r *http.Request) http.Header { 1.36 + res := http.Header{} 1.37 + for h, v := range r.Header { 1.38 + stripped := strings.TrimPrefix(h, http.CanonicalHeaderKey("Trout-Param-")) 1.39 + if stripped != h { 1.40 + res[stripped] = v 1.41 + } 1.42 + } 1.43 + return res 1.44 +} 1.45 + 1.46 +// Router defines a set of Endpoints that map requests to the http.Handlers. The http.Handler assigned to 1.47 +// Handle404, if set, will be called when no Endpoint matches the current request. The http.Handler assigned 1.48 +// to Handle405, if set, will be called when an Endpoint matches the current request, but has no http.Handler 1.49 +// set for the HTTP method that the request used. Should either of these properties be unset, a default 1.50 +// http.Handler will be used. 1.51 +// 1.52 +// The Router type is safe for use with empty values, but makes no attempt at concurrency-safety in adding 1.53 +// Endpoints or in setting properties. It should also be noted that the adding Endpoints while simultaneously 1.54 +// routing requests will lead to undefined and (almost certainly) undesirable behaviour. Routers are intended 1.55 +// to be initialised with a set of Endpoints, and then start serving requests. Using them outside of this use 1.56 +// case is unsupported. 1.57 +type Router struct { 1.58 + t *trie 1.59 + Handle404 http.Handler 1.60 + Handle405 http.Handler 1.61 +} 1.62 + 1.63 +func (router Router) serve404(w http.ResponseWriter, r *http.Request, t time.Time) { 1.64 + h := default404Handler 1.65 + if router.Handle404 != nil { 1.66 + h = router.Handle404 1.67 + } 1.68 + r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10)) 1.69 + h.ServeHTTP(w, r) 1.70 +} 1.71 + 1.72 +func (router Router) serve405(w http.ResponseWriter, r *http.Request, t time.Time) { 1.73 + h := default405Handler 1.74 + if router.Handle405 != nil { 1.75 + h = router.Handle405 1.76 + } 1.77 + r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10)) 1.78 + h.ServeHTTP(w, r) 1.79 +} 1.80 + 1.81 +func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { 1.82 + start := time.Now() 1.83 + if router.t == nil { 1.84 + router.serve404(w, r, start) 1.85 + } 1.86 + pieces := strings.Split(strings.ToLower(strings.Trim(r.URL.Path, "/")), "/") 1.87 + router.t.RLock() 1.88 + defer router.t.RUnlock() 1.89 + branches := make([]*branch, len(pieces)) 1.90 + path, ok := router.t.match(pieces) 1.91 + if !ok { 1.92 + router.serve404(w, r, start) 1.93 + } 1.94 + b := router.t.branch 1.95 + for i, pos := range path { 1.96 + b = b.children[pos] 1.97 + branches[i] = b 1.98 + } 1.99 + v := vars(branches, pieces) 1.100 + for key, vals := range v { 1.101 + r.Header[http.CanonicalHeaderKey("Trout-Param-"+key)] = vals 1.102 + } 1.103 + ms := make([]string, len(b.methods)) 1.104 + i := 0 1.105 + for m := range b.methods { 1.106 + ms[i] = m 1.107 + i = i + 1 1.108 + } 1.109 + r.Header[http.CanonicalHeaderKey("Trout-Methods")] = ms 1.110 + h := b.methods[r.Method] 1.111 + if h == nil { 1.112 + router.serve405(w, r, start) 1.113 + } 1.114 + r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(start).Nanoseconds(), 10)) 1.115 + h.ServeHTTP(w, r) 1.116 +} 1.117 + 1.118 +// Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces 1.119 +// to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id` 1.120 +// that should be filled with whatever the request has in that space. 1.121 +// 1.122 +// Parameters are always `/`-separated strings. There is no support for regular expressions or other limitations 1.123 +// on what may be in those strings. A parameter is simply defined as "whatever is between these two / characters". 1.124 +func (router Router) Endpoint(e string) *Endpoint { 1.125 + e = strings.Trim(e, "/") 1.126 + e = strings.ToLower(e) 1.127 + pieces := strings.Split(e, "/") 1.128 + router.t.Lock() 1.129 + defer router.t.Unlock() 1.130 + if router.t.branch == nil { 1.131 + router.t.branch = &branch{ 1.132 + parent: nil, 1.133 + children: []*branch{}, 1.134 + key: "", 1.135 + isParam: false, 1.136 + methods: map[string]http.Handler{}, 1.137 + } 1.138 + } 1.139 + closest := findClosestLeaf(pieces, router.t.branch) 1.140 + b := router.t.branch 1.141 + for _, pos := range closest { 1.142 + b = b.children[pos] 1.143 + } 1.144 + if len(closest) == len(pieces) { 1.145 + return (*Endpoint)(b) 1.146 + } 1.147 + offset := len(closest) 1.148 + for i := offset; i < len(pieces); i++ { 1.149 + piece := pieces[i] 1.150 + var isParam bool 1.151 + if piece[0:1] == "{" && piece[len(piece)-1:] == "}" { 1.152 + isParam = true 1.153 + piece = piece[1 : len(piece)-1] 1.154 + } 1.155 + b = b.addChild(piece, isParam) 1.156 + } 1.157 + return (*Endpoint)(b) 1.158 +} 1.159 + 1.160 +func vars(path []*branch, pieces []string) map[string][]string { 1.161 + v := map[string][]string{} 1.162 + for pos, p := range path { 1.163 + if !p.isParam { 1.164 + continue 1.165 + } 1.166 + _, ok := v[p.key] 1.167 + if !ok { 1.168 + v[p.key] = []string{pieces[pos]} 1.169 + continue 1.170 + } 1.171 + v[p.key] = append(v[p.key], pieces[pos]) 1.172 + } 1.173 + return v 1.174 +} 1.175 + 1.176 +func findClosestLeaf(pieces []string, b *branch) []int { 1.177 + offset := 0 1.178 + path := []int{} 1.179 + longest := []int{} 1.180 + num := len(pieces) 1.181 + for i := 0; i < num; i++ { 1.182 + piece := pieces[i] 1.183 + var isParam bool 1.184 + if piece[0:1] == "{" && piece[len(piece)-1:] == "}" { 1.185 + isParam = true 1.186 + piece = piece[1 : len(piece)-1] 1.187 + } 1.188 + offset = pickNextRoute(b, offset, piece, isParam) 1.189 + if offset == -1 { 1.190 + if len(path) == 0 { 1.191 + // exhausted our options, bail 1.192 + break 1.193 + } 1.194 + // no match, maybe save this and backup 1.195 + if len(path) > len(longest) { 1.196 + longest = append([]int{}, path...) // copy them over so they don't get modified 1.197 + } 1.198 + path, offset = backup(path) 1.199 + offset = offset + 1 1.200 + b = b.parent 1.201 + i = i - 2 1.202 + } else { 1.203 + path = append(path, offset) 1.204 + b = b.children[offset] 1.205 + offset = 0 1.206 + } 1.207 + } 1.208 + if len(longest) < len(path) { 1.209 + longest = append([]int{}, path...) 1.210 + } 1.211 + return longest 1.212 +} 1.213 + 1.214 +func pickNextRoute(b *branch, offset int, input string, variable bool) int { 1.215 + count := len(b.children) 1.216 + for i := offset; i < count; i++ { 1.217 + if b.children[i].key == input && b.isParam == variable { 1.218 + return i 1.219 + } 1.220 + } 1.221 + return -1 1.222 +} 1.223 + 1.224 +// Endpoint defines a single URL template that requests can be matched against. It uses 1.225 +// URL parameters to accept variables in the URL structure and make them available to 1.226 +// the Handlers associated with the Endpoint. 1.227 +type Endpoint branch 1.228 + 1.229 +// Handler associates the passed http.Handler with the Endpoint. This http.Handler will be 1.230 +// used for all requests, regardless of the HTTP method they are using, unless overridden by 1.231 +// the Methods method. Endpoints without a http.Handler associated with them will not be 1.232 +// considered matches for requests, unless the request was made using an HTTP method that the 1.233 +// Endpoint has an http.Handler mapped to. 1.234 +func (e *Endpoint) Handler(h http.Handler) { 1.235 + (*branch)(e).setHandler("", h) 1.236 +} 1.237 + 1.238 +// Methods simple returns a Methods object that will enable the mapping of the passed HTTP 1.239 +// request methods to a Methods object. On its own, this function does not modify anything. It 1.240 +// should, instead, be used as a friendly shorthand to get to the Methods.Handler method. 1.241 +func (e *Endpoint) Methods(m ...string) Methods { 1.242 + return Methods{ 1.243 + e: e, 1.244 + m: m, 1.245 + } 1.246 +} 1.247 + 1.248 +// Methods defines a pairing of an Endpoint to the HTTP request methods that should be mapped to 1.249 +// specific http.Handlers. Its sole purpose is to enable the Methods.Handler method. 1.250 +type Methods struct { 1.251 + e *Endpoint 1.252 + m []string 1.253 +} 1.254 + 1.255 +// Handler maps a Methods object to a specific http.Handler. This overrides the http.Handler 1.256 +// associated with the Endpoint to only handle specific HTTP method(s). 1.257 +func (m Methods) Handler(h http.Handler) { 1.258 + b := (*branch)(m.e) 1.259 + for _, method := range m.m { 1.260 + b.setHandler(method, h) 1.261 + } 1.262 +}