1
// Copyright 2012 The Gorilla Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
6
Package gorilla/pat is a request router and dispatcher with a pat-like
7
interface. It is an alternative to gorilla/mux that showcases how it can
8
be used as a base for different API flavors. Package pat is documented at:
10
http://gopkgdoc.appspot.com/pkg/github.com/bmizerany/pat
12
Let's start registering a couple of URL paths and handlers:
16
r.Get("/", HomeHandler)
17
r.Get("/products", ProductsHandler)
18
r.Get("/articles", ArticlesHandler)
22
Here we register three routes mapping URL paths to handlers. This is
23
equivalent to how http.HandleFunc() works: if an incoming GET request matches
24
one of the paths, the corresponding handler is called passing
25
(http.ResponseWriter, *http.Request) as parameters.
27
Note: differently from pat, these methods accept a handler function, and not an
28
http.Handler. We think this is shorter and more convenient. To set an
29
http.Handler, use the Add() method.
31
Paths can have variables. They are defined using the format {name} or
32
{name:pattern}. If a regular expression pattern is not defined, the matched
33
variable will be anything until the next slash. For example:
36
r.Get("/products/{key}", ProductHandler)
37
r.Get("/articles/{category}/", ArticlesCategoryHandler)
38
r.Get("/articles/{category}/{id:[0-9]+}", ArticleHandler)
40
The names are used to create a map of route variables which are stored in the
41
URL query, prefixed by a colon:
43
category := req.URL.Query().Get(":category")
45
As in the gorilla/mux package, other matchers can be added to the registered
46
routes and URLs can be reversed as well. To build a URL for a route, first
49
r.Get("/products/{key}", ProductHandler).Name("product")
51
Then you can get it using the name and generate a URL:
53
url, err := r.GetRoute("product").URL("key", "transmogrifier")
55
...and the result will be a url.URL with the following path:
57
"/products/transmogrifier"
59
Check the mux documentation for more details about URL building and extra
62
http://gorilla-web.appspot.com/pkg/gorilla/mux/