1// Copyright 2013 Julien Schmidt. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be found
3// in the LICENSE file.
4
5// Package httprouter is a trie based high performance HTTP request router.
6//
7// A trivial example is:
8//
9//  package main
10//
11//  import (
12//      "fmt"
13//      "github.com/julienschmidt/httprouter"
14//      "net/http"
15//      "log"
16//  )
17//
18//  func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
19//      fmt.Fprint(w, "Welcome!\n")
20//  }
21//
22//  func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
23//      fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
24//  }
25//
26//  func main() {
27//      router := httprouter.New()
28//      router.GET("/", Index)
29//      router.GET("/hello/:name", Hello)
30//
31//      log.Fatal(http.ListenAndServe(":8080", router))
32//  }
33//
34// The router matches incoming requests by the request method and the path.
35// If a handle is registered for this path and method, the router delegates the
36// request to that function.
37// For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
38// register handles, for all other methods router.Handle can be used.
39//
40// The registered path, against which the router matches incoming requests, can
41// contain two types of parameters:
42//  Syntax    Type
43//  :name     named parameter
44//  *name     catch-all parameter
45//
46// Named parameters are dynamic path segments. They match anything until the
47// next '/' or the path end:
48//  Path: /blog/:category/:post
49//
50//  Requests:
51//   /blog/go/request-routers            match: category="go", post="request-routers"
52//   /blog/go/request-routers/           no match, but the router would redirect
53//   /blog/go/                           no match
54//   /blog/go/request-routers/comments   no match
55//
56// Catch-all parameters match anything until the path end, including the
57// directory index (the '/' before the catch-all). Since they match anything
58// until the end, catch-all parameters must always be the final path element.
59//  Path: /files/*filepath
60//
61//  Requests:
62//   /files/                             match: filepath="/"
63//   /files/LICENSE                      match: filepath="/LICENSE"
64//   /files/templates/article.html       match: filepath="/templates/article.html"
65//   /files                              no match, but the router would redirect
66//
67// The value of parameters is saved as a slice of the Param struct, consisting
68// each of a key and a value. The slice is passed to the Handle func as a third
69// parameter.
70// There are two ways to retrieve the value of a parameter:
71//  // by the name of the parameter
72//  user := ps.ByName("user") // defined by :user or *user
73//
74//  // by the index of the parameter. This way you can also get the name (key)
75//  thirdKey   := ps[2].Key   // the name of the 3rd parameter
76//  thirdValue := ps[2].Value // the value of the 3rd parameter
77package httprouter
78
79import (
80	"context"
81	"net/http"
82	"strings"
83)
84
85// Handle is a function that can be registered to a route to handle HTTP
86// requests. Like http.HandlerFunc, but has a third parameter for the values of
87// wildcards (variables).
88type Handle func(http.ResponseWriter, *http.Request, Params)
89
90// Param is a single URL parameter, consisting of a key and a value.
91type Param struct {
92	Key   string
93	Value string
94}
95
96// Params is a Param-slice, as returned by the router.
97// The slice is ordered, the first URL parameter is also the first slice value.
98// It is therefore safe to read values by the index.
99type Params []Param
100
101// ByName returns the value of the first Param which key matches the given name.
102// If no matching Param is found, an empty string is returned.
103func (ps Params) ByName(name string) string {
104	for i := range ps {
105		if ps[i].Key == name {
106			return ps[i].Value
107		}
108	}
109	return ""
110}
111
112type paramsKey struct{}
113
114// ParamsKey is the request context key under which URL params are stored.
115var ParamsKey = paramsKey{}
116
117// ParamsFromContext pulls the URL parameters from a request context,
118// or returns nil if none are present.
119func ParamsFromContext(ctx context.Context) Params {
120	p, _ := ctx.Value(ParamsKey).(Params)
121	return p
122}
123
124// Router is a http.Handler which can be used to dispatch requests to different
125// handler functions via configurable routes
126type Router struct {
127	trees map[string]*node
128
129	// Enables automatic redirection if the current route can't be matched but a
130	// handler for the path with (without) the trailing slash exists.
131	// For example if /foo/ is requested but a route only exists for /foo, the
132	// client is redirected to /foo with http status code 301 for GET requests
133	// and 307 for all other request methods.
134	RedirectTrailingSlash bool
135
136	// If enabled, the router tries to fix the current request path, if no
137	// handle is registered for it.
138	// First superfluous path elements like ../ or // are removed.
139	// Afterwards the router does a case-insensitive lookup of the cleaned path.
140	// If a handle can be found for this route, the router makes a redirection
141	// to the corrected path with status code 301 for GET requests and 307 for
142	// all other request methods.
143	// For example /FOO and /..//Foo could be redirected to /foo.
144	// RedirectTrailingSlash is independent of this option.
145	RedirectFixedPath bool
146
147	// If enabled, the router checks if another method is allowed for the
148	// current route, if the current request can not be routed.
149	// If this is the case, the request is answered with 'Method Not Allowed'
150	// and HTTP status code 405.
151	// If no other Method is allowed, the request is delegated to the NotFound
152	// handler.
153	HandleMethodNotAllowed bool
154
155	// If enabled, the router automatically replies to OPTIONS requests.
156	// Custom OPTIONS handlers take priority over automatic replies.
157	HandleOPTIONS bool
158
159	// An optional http.Handler that is called on automatic OPTIONS requests.
160	// The handler is only called if HandleOPTIONS is true and no OPTIONS
161	// handler for the specific path was set.
162	// The "Allowed" header is set before calling the handler.
163	GlobalOPTIONS http.Handler
164
165	// Cached value of global (*) allowed methods
166	globalAllowed string
167
168	// Configurable http.Handler which is called when no matching route is
169	// found. If it is not set, http.NotFound is used.
170	NotFound http.Handler
171
172	// Configurable http.Handler which is called when a request
173	// cannot be routed and HandleMethodNotAllowed is true.
174	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
175	// The "Allow" header with allowed request methods is set before the handler
176	// is called.
177	MethodNotAllowed http.Handler
178
179	// Function to handle panics recovered from http handlers.
180	// It should be used to generate a error page and return the http error code
181	// 500 (Internal Server Error).
182	// The handler can be used to keep your server from crashing because of
183	// unrecovered panics.
184	PanicHandler func(http.ResponseWriter, *http.Request, interface{})
185}
186
187// Make sure the Router conforms with the http.Handler interface
188var _ http.Handler = New()
189
190// New returns a new initialized Router.
191// Path auto-correction, including trailing slashes, is enabled by default.
192func New() *Router {
193	return &Router{
194		RedirectTrailingSlash:  true,
195		RedirectFixedPath:      true,
196		HandleMethodNotAllowed: true,
197		HandleOPTIONS:          true,
198	}
199}
200
201// GET is a shortcut for router.Handle(http.MethodGet, path, handle)
202func (r *Router) GET(path string, handle Handle) {
203	r.Handle(http.MethodGet, path, handle)
204}
205
206// HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)
207func (r *Router) HEAD(path string, handle Handle) {
208	r.Handle(http.MethodHead, path, handle)
209}
210
211// OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)
212func (r *Router) OPTIONS(path string, handle Handle) {
213	r.Handle(http.MethodOptions, path, handle)
214}
215
216// POST is a shortcut for router.Handle(http.MethodPost, path, handle)
217func (r *Router) POST(path string, handle Handle) {
218	r.Handle(http.MethodPost, path, handle)
219}
220
221// PUT is a shortcut for router.Handle(http.MethodPut, path, handle)
222func (r *Router) PUT(path string, handle Handle) {
223	r.Handle(http.MethodPut, path, handle)
224}
225
226// PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)
227func (r *Router) PATCH(path string, handle Handle) {
228	r.Handle(http.MethodPatch, path, handle)
229}
230
231// DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)
232func (r *Router) DELETE(path string, handle Handle) {
233	r.Handle(http.MethodDelete, path, handle)
234}
235
236// Handle registers a new request handle with the given path and method.
237//
238// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
239// functions can be used.
240//
241// This function is intended for bulk loading and to allow the usage of less
242// frequently used, non-standardized or custom methods (e.g. for internal
243// communication with a proxy).
244func (r *Router) Handle(method, path string, handle Handle) {
245	if len(path) < 1 || path[0] != '/' {
246		panic("path must begin with '/' in path '" + path + "'")
247	}
248
249	if r.trees == nil {
250		r.trees = make(map[string]*node)
251	}
252
253	root := r.trees[method]
254	if root == nil {
255		root = new(node)
256		r.trees[method] = root
257
258		r.globalAllowed = r.allowed("*", "")
259	}
260
261	root.addRoute(path, handle)
262}
263
264// Handler is an adapter which allows the usage of an http.Handler as a
265// request handle.
266// The Params are available in the request context under ParamsKey.
267func (r *Router) Handler(method, path string, handler http.Handler) {
268	r.Handle(method, path,
269		func(w http.ResponseWriter, req *http.Request, p Params) {
270			if len(p) > 0 {
271				ctx := req.Context()
272				ctx = context.WithValue(ctx, ParamsKey, p)
273				req = req.WithContext(ctx)
274			}
275			handler.ServeHTTP(w, req)
276		},
277	)
278}
279
280// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
281// request handle.
282func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
283	r.Handler(method, path, handler)
284}
285
286// ServeFiles serves files from the given file system root.
287// The path must end with "/*filepath", files are then served from the local
288// path /defined/root/dir/*filepath.
289// For example if root is "/etc" and *filepath is "passwd", the local file
290// "/etc/passwd" would be served.
291// Internally a http.FileServer is used, therefore http.NotFound is used instead
292// of the Router's NotFound handler.
293// To use the operating system's file system implementation,
294// use http.Dir:
295//     router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
296func (r *Router) ServeFiles(path string, root http.FileSystem) {
297	if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
298		panic("path must end with /*filepath in path '" + path + "'")
299	}
300
301	fileServer := http.FileServer(root)
302
303	r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
304		req.URL.Path = ps.ByName("filepath")
305		fileServer.ServeHTTP(w, req)
306	})
307}
308
309func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
310	if rcv := recover(); rcv != nil {
311		r.PanicHandler(w, req, rcv)
312	}
313}
314
315// Lookup allows the manual lookup of a method + path combo.
316// This is e.g. useful to build a framework around this router.
317// If the path was found, it returns the handle function and the path parameter
318// values. Otherwise the third return value indicates whether a redirection to
319// the same path with an extra / without the trailing slash should be performed.
320func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
321	if root := r.trees[method]; root != nil {
322		return root.getValue(path)
323	}
324	return nil, nil, false
325}
326
327func (r *Router) allowed(path, reqMethod string) (allow string) {
328	allowed := make([]string, 0, 9)
329
330	if path == "*" { // server-wide
331		// empty method is used for internal calls to refresh the cache
332		if reqMethod == "" {
333			for method := range r.trees {
334				if method == http.MethodOptions {
335					continue
336				}
337				// Add request method to list of allowed methods
338				allowed = append(allowed, method)
339			}
340		} else {
341			return r.globalAllowed
342		}
343	} else { // specific path
344		for method := range r.trees {
345			// Skip the requested method - we already tried this one
346			if method == reqMethod || method == http.MethodOptions {
347				continue
348			}
349
350			handle, _, _ := r.trees[method].getValue(path)
351			if handle != nil {
352				// Add request method to list of allowed methods
353				allowed = append(allowed, method)
354			}
355		}
356	}
357
358	if len(allowed) > 0 {
359		// Add request method to list of allowed methods
360		allowed = append(allowed, http.MethodOptions)
361
362		// Sort allowed methods.
363		// sort.Strings(allowed) unfortunately causes unnecessary allocations
364		// due to allowed being moved to the heap and interface conversion
365		for i, l := 1, len(allowed); i < l; i++ {
366			for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- {
367				allowed[j], allowed[j-1] = allowed[j-1], allowed[j]
368			}
369		}
370
371		// return as comma separated list
372		return strings.Join(allowed, ", ")
373	}
374	return
375}
376
377// ServeHTTP makes the router implement the http.Handler interface.
378func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
379	if r.PanicHandler != nil {
380		defer r.recv(w, req)
381	}
382
383	path := req.URL.Path
384
385	if root := r.trees[req.Method]; root != nil {
386		if handle, ps, tsr := root.getValue(path); handle != nil {
387			handle(w, req, ps)
388			return
389		} else if req.Method != http.MethodConnect && path != "/" {
390			code := 301 // Permanent redirect, request with GET method
391			if req.Method != http.MethodGet {
392				// Temporary redirect, request with same method
393				// As of Go 1.3, Go does not support status code 308.
394				code = 307
395			}
396
397			if tsr && r.RedirectTrailingSlash {
398				if len(path) > 1 && path[len(path)-1] == '/' {
399					req.URL.Path = path[:len(path)-1]
400				} else {
401					req.URL.Path = path + "/"
402				}
403				http.Redirect(w, req, req.URL.String(), code)
404				return
405			}
406
407			// Try to fix the request path
408			if r.RedirectFixedPath {
409				fixedPath, found := root.findCaseInsensitivePath(
410					CleanPath(path),
411					r.RedirectTrailingSlash,
412				)
413				if found {
414					req.URL.Path = string(fixedPath)
415					http.Redirect(w, req, req.URL.String(), code)
416					return
417				}
418			}
419		}
420	}
421
422	if req.Method == http.MethodOptions && r.HandleOPTIONS {
423		// Handle OPTIONS requests
424		if allow := r.allowed(path, http.MethodOptions); allow != "" {
425			w.Header().Set("Allow", allow)
426			if r.GlobalOPTIONS != nil {
427				r.GlobalOPTIONS.ServeHTTP(w, req)
428			}
429			return
430		}
431	} else if r.HandleMethodNotAllowed { // Handle 405
432		if allow := r.allowed(path, req.Method); allow != "" {
433			w.Header().Set("Allow", allow)
434			if r.MethodNotAllowed != nil {
435				r.MethodNotAllowed.ServeHTTP(w, req)
436			} else {
437				http.Error(w,
438					http.StatusText(http.StatusMethodNotAllowed),
439					http.StatusMethodNotAllowed,
440				)
441			}
442			return
443		}
444	}
445
446	// Handle 404
447	if r.NotFound != nil {
448		r.NotFound.ServeHTTP(w, req)
449	} else {
450		http.NotFound(w, req)
451	}
452}
453