You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 25 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. # gorilla/mux
  2. [![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
  3. [![CircleCI](https://circleci.com/gh/gorilla/mux.svg?style=svg)](https://circleci.com/gh/gorilla/mux)
  4. [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
  5. ![Gorilla Logo](https://cloud-cdn.questionable.services/gorilla-icon-64.png)
  6. https://www.gorillatoolkit.org/pkg/mux
  7. Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to
  8. their respective handler.
  9. The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are:
  10. * It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
  11. * Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
  12. * URL hosts, paths and query values can have variables with an optional regular expression.
  13. * Registered URLs can be built, or "reversed", which helps maintaining references to resources.
  14. * Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
  15. ---
  16. * [Install](#install)
  17. * [Examples](#examples)
  18. * [Matching Routes](#matching-routes)
  19. * [Static Files](#static-files)
  20. * [Serving Single Page Applications](#serving-single-page-applications) (e.g. React, Vue, Ember.js, etc.)
  21. * [Registered URLs](#registered-urls)
  22. * [Walking Routes](#walking-routes)
  23. * [Graceful Shutdown](#graceful-shutdown)
  24. * [Middleware](#middleware)
  25. * [Handling CORS Requests](#handling-cors-requests)
  26. * [Testing Handlers](#testing-handlers)
  27. * [Full Example](#full-example)
  28. ---
  29. ## Install
  30. With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain:
  31. ```sh
  32. go get -u github.com/gorilla/mux
  33. ```
  34. ## Examples
  35. Let's start registering a couple of URL paths and handlers:
  36. ```go
  37. func main() {
  38. r := mux.NewRouter()
  39. r.HandleFunc("/", HomeHandler)
  40. r.HandleFunc("/products", ProductsHandler)
  41. r.HandleFunc("/articles", ArticlesHandler)
  42. http.Handle("/", r)
  43. }
  44. ```
  45. Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters.
  46. Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
  47. ```go
  48. r := mux.NewRouter()
  49. r.HandleFunc("/products/{key}", ProductHandler)
  50. r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
  51. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  52. ```
  53. The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`:
  54. ```go
  55. func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
  56. vars := mux.Vars(r)
  57. w.WriteHeader(http.StatusOK)
  58. fmt.Fprintf(w, "Category: %v\n", vars["category"])
  59. }
  60. ```
  61. And this is all you need to know about the basic usage. More advanced options are explained below.
  62. ### Matching Routes
  63. Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
  64. ```go
  65. r := mux.NewRouter()
  66. // Only matches if domain is "www.example.com".
  67. r.Host("www.example.com")
  68. // Matches a dynamic subdomain.
  69. r.Host("{subdomain:[a-z]+}.example.com")
  70. ```
  71. There are several other matchers that can be added. To match path prefixes:
  72. ```go
  73. r.PathPrefix("/products/")
  74. ```
  75. ...or HTTP methods:
  76. ```go
  77. r.Methods("GET", "POST")
  78. ```
  79. ...or URL schemes:
  80. ```go
  81. r.Schemes("https")
  82. ```
  83. ...or header values:
  84. ```go
  85. r.Headers("X-Requested-With", "XMLHttpRequest")
  86. ```
  87. ...or query values:
  88. ```go
  89. r.Queries("key", "value")
  90. ```
  91. ...or to use a custom matcher function:
  92. ```go
  93. r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
  94. return r.ProtoMajor == 0
  95. })
  96. ```
  97. ...and finally, it is possible to combine several matchers in a single route:
  98. ```go
  99. r.HandleFunc("/products", ProductsHandler).
  100. Host("www.example.com").
  101. Methods("GET").
  102. Schemes("http")
  103. ```
  104. Routes are tested in the order they were added to the router. If two routes match, the first one wins:
  105. ```go
  106. r := mux.NewRouter()
  107. r.HandleFunc("/specific", specificHandler)
  108. r.PathPrefix("/").Handler(catchAllHandler)
  109. ```
  110. Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting".
  111. For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it:
  112. ```go
  113. r := mux.NewRouter()
  114. s := r.Host("www.example.com").Subrouter()
  115. ```
  116. Then register routes in the subrouter:
  117. ```go
  118. s.HandleFunc("/products/", ProductsHandler)
  119. s.HandleFunc("/products/{key}", ProductHandler)
  120. s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  121. ```
  122. The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route.
  123. Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
  124. There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
  125. ```go
  126. r := mux.NewRouter()
  127. s := r.PathPrefix("/products").Subrouter()
  128. // "/products/"
  129. s.HandleFunc("/", ProductsHandler)
  130. // "/products/{key}/"
  131. s.HandleFunc("/{key}/", ProductHandler)
  132. // "/products/{key}/details"
  133. s.HandleFunc("/{key}/details", ProductDetailsHandler)
  134. ```
  135. ### Static Files
  136. Note that the path provided to `PathPrefix()` represents a "wildcard": calling
  137. `PathPrefix("/static/").Handler(...)` means that the handler will be passed any
  138. request that matches "/static/\*". This makes it easy to serve static files with mux:
  139. ```go
  140. func main() {
  141. var dir string
  142. flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
  143. flag.Parse()
  144. r := mux.NewRouter()
  145. // This will serve files under http://localhost:8000/static/<filename>
  146. r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
  147. srv := &http.Server{
  148. Handler: r,
  149. Addr: "127.0.0.1:8000",
  150. // Good practice: enforce timeouts for servers you create!
  151. WriteTimeout: 15 * time.Second,
  152. ReadTimeout: 15 * time.Second,
  153. }
  154. log.Fatal(srv.ListenAndServe())
  155. }
  156. ```
  157. ### Serving Single Page Applications
  158. Most of the time it makes sense to serve your SPA on a separate web server from your API,
  159. but sometimes it's desirable to serve them both from one place. It's possible to write a simple
  160. handler for serving your SPA (for use with React Router's [BrowserRouter](https://reacttraining.com/react-router/web/api/BrowserRouter) for example), and leverage
  161. mux's powerful routing for your API endpoints.
  162. ```go
  163. package main
  164. import (
  165. "encoding/json"
  166. "log"
  167. "net/http"
  168. "os"
  169. "path/filepath"
  170. "time"
  171. "github.com/gorilla/mux"
  172. )
  173. // spaHandler implements the http.Handler interface, so we can use it
  174. // to respond to HTTP requests. The path to the static directory and
  175. // path to the index file within that static directory are used to
  176. // serve the SPA in the given static directory.
  177. type spaHandler struct {
  178. staticPath string
  179. indexPath string
  180. }
  181. // ServeHTTP inspects the URL path to locate a file within the static dir
  182. // on the SPA handler. If a file is found, it will be served. If not, the
  183. // file located at the index path on the SPA handler will be served. This
  184. // is suitable behavior for serving an SPA (single page application).
  185. func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  186. // get the absolute path to prevent directory traversal
  187. path, err := filepath.Abs(r.URL.Path)
  188. if err != nil {
  189. // if we failed to get the absolute path respond with a 400 bad request
  190. // and stop
  191. http.Error(w, err.Error(), http.StatusBadRequest)
  192. return
  193. }
  194. // prepend the path with the path to the static directory
  195. path = filepath.Join(h.staticPath, path)
  196. // check whether a file exists at the given path
  197. _, err = os.Stat(path)
  198. if os.IsNotExist(err) {
  199. // file does not exist, serve index.html
  200. http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
  201. return
  202. } else if err != nil {
  203. // if we got an error (that wasn't that the file doesn't exist) stating the
  204. // file, return a 500 internal server error and stop
  205. http.Error(w, err.Error(), http.StatusInternalServerError)
  206. return
  207. }
  208. // otherwise, use http.FileServer to serve the static dir
  209. http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
  210. }
  211. func main() {
  212. router := mux.NewRouter()
  213. router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
  214. // an example API handler
  215. json.NewEncoder(w).Encode(map[string]bool{"ok": true})
  216. })
  217. spa := spaHandler{staticPath: "build", indexPath: "index.html"}
  218. router.PathPrefix("/").Handler(spa)
  219. srv := &http.Server{
  220. Handler: router,
  221. Addr: "127.0.0.1:8000",
  222. // Good practice: enforce timeouts for servers you create!
  223. WriteTimeout: 15 * time.Second,
  224. ReadTimeout: 15 * time.Second,
  225. }
  226. log.Fatal(srv.ListenAndServe())
  227. }
  228. ```
  229. ### Registered URLs
  230. Now let's see how to build registered URLs.
  231. Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example:
  232. ```go
  233. r := mux.NewRouter()
  234. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  235. Name("article")
  236. ```
  237. To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do:
  238. ```go
  239. url, err := r.Get("article").URL("category", "technology", "id", "42")
  240. ```
  241. ...and the result will be a `url.URL` with the following path:
  242. ```
  243. "/articles/technology/42"
  244. ```
  245. This also works for host and query value variables:
  246. ```go
  247. r := mux.NewRouter()
  248. r.Host("{subdomain}.example.com").
  249. Path("/articles/{category}/{id:[0-9]+}").
  250. Queries("filter", "{filter}").
  251. HandlerFunc(ArticleHandler).
  252. Name("article")
  253. // url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla"
  254. url, err := r.Get("article").URL("subdomain", "news",
  255. "category", "technology",
  256. "id", "42",
  257. "filter", "gorilla")
  258. ```
  259. All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match.
  260. Regex support also exists for matching Headers within a route. For example, we could do:
  261. ```go
  262. r.HeadersRegexp("Content-Type", "application/(text|json)")
  263. ```
  264. ...and the route will match both requests with a Content-Type of `application/json` as well as `application/text`
  265. There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do:
  266. ```go
  267. // "http://news.example.com/"
  268. host, err := r.Get("article").URLHost("subdomain", "news")
  269. // "/articles/technology/42"
  270. path, err := r.Get("article").URLPath("category", "technology", "id", "42")
  271. ```
  272. And if you use subrouters, host and path defined separately can be built as well:
  273. ```go
  274. r := mux.NewRouter()
  275. s := r.Host("{subdomain}.example.com").Subrouter()
  276. s.Path("/articles/{category}/{id:[0-9]+}").
  277. HandlerFunc(ArticleHandler).
  278. Name("article")
  279. // "http://news.example.com/articles/technology/42"
  280. url, err := r.Get("article").URL("subdomain", "news",
  281. "category", "technology",
  282. "id", "42")
  283. ```
  284. ### Walking Routes
  285. The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example,
  286. the following prints all of the registered routes:
  287. ```go
  288. package main
  289. import (
  290. "fmt"
  291. "net/http"
  292. "strings"
  293. "github.com/gorilla/mux"
  294. )
  295. func handler(w http.ResponseWriter, r *http.Request) {
  296. return
  297. }
  298. func main() {
  299. r := mux.NewRouter()
  300. r.HandleFunc("/", handler)
  301. r.HandleFunc("/products", handler).Methods("POST")
  302. r.HandleFunc("/articles", handler).Methods("GET")
  303. r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
  304. r.HandleFunc("/authors", handler).Queries("surname", "{surname}")
  305. err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
  306. pathTemplate, err := route.GetPathTemplate()
  307. if err == nil {
  308. fmt.Println("ROUTE:", pathTemplate)
  309. }
  310. pathRegexp, err := route.GetPathRegexp()
  311. if err == nil {
  312. fmt.Println("Path regexp:", pathRegexp)
  313. }
  314. queriesTemplates, err := route.GetQueriesTemplates()
  315. if err == nil {
  316. fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
  317. }
  318. queriesRegexps, err := route.GetQueriesRegexp()
  319. if err == nil {
  320. fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
  321. }
  322. methods, err := route.GetMethods()
  323. if err == nil {
  324. fmt.Println("Methods:", strings.Join(methods, ","))
  325. }
  326. fmt.Println()
  327. return nil
  328. })
  329. if err != nil {
  330. fmt.Println(err)
  331. }
  332. http.Handle("/", r)
  333. }
  334. ```
  335. ### Graceful Shutdown
  336. Go 1.8 introduced the ability to [gracefully shutdown](https://golang.org/doc/go1.8#http_shutdown) a `*http.Server`. Here's how to do that alongside `mux`:
  337. ```go
  338. package main
  339. import (
  340. "context"
  341. "flag"
  342. "log"
  343. "net/http"
  344. "os"
  345. "os/signal"
  346. "time"
  347. "github.com/gorilla/mux"
  348. )
  349. func main() {
  350. var wait time.Duration
  351. flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
  352. flag.Parse()
  353. r := mux.NewRouter()
  354. // Add your routes as needed
  355. srv := &http.Server{
  356. Addr: "0.0.0.0:8080",
  357. // Good practice to set timeouts to avoid Slowloris attacks.
  358. WriteTimeout: time.Second * 15,
  359. ReadTimeout: time.Second * 15,
  360. IdleTimeout: time.Second * 60,
  361. Handler: r, // Pass our instance of gorilla/mux in.
  362. }
  363. // Run our server in a goroutine so that it doesn't block.
  364. go func() {
  365. if err := srv.ListenAndServe(); err != nil {
  366. log.Println(err)
  367. }
  368. }()
  369. c := make(chan os.Signal, 1)
  370. // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
  371. // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
  372. signal.Notify(c, os.Interrupt)
  373. // Block until we receive our signal.
  374. <-c
  375. // Create a deadline to wait for.
  376. ctx, cancel := context.WithTimeout(context.Background(), wait)
  377. defer cancel()
  378. // Doesn't block if no connections, but will otherwise wait
  379. // until the timeout deadline.
  380. srv.Shutdown(ctx)
  381. // Optionally, you could run srv.Shutdown in a goroutine and block on
  382. // <-ctx.Done() if your application should wait for other services
  383. // to finalize based on context cancellation.
  384. log.Println("shutting down")
  385. os.Exit(0)
  386. }
  387. ```
  388. ### Middleware
  389. Mux supports the addition of middlewares to a [Router](https://godoc.org/github.com/gorilla/mux#Router), which are executed in the order they are added if a match is found, including its subrouters.
  390. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or `ResponseWriter` hijacking.
  391. Mux middlewares are defined using the de facto standard type:
  392. ```go
  393. type MiddlewareFunc func(http.Handler) http.Handler
  394. ```
  395. Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc. This takes advantage of closures being able access variables from the context where they are created, while retaining the signature enforced by the receivers.
  396. A very basic middleware which logs the URI of the request being handled could be written as:
  397. ```go
  398. func loggingMiddleware(next http.Handler) http.Handler {
  399. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  400. // Do stuff here
  401. log.Println(r.RequestURI)
  402. // Call the next handler, which can be another middleware in the chain, or the final handler.
  403. next.ServeHTTP(w, r)
  404. })
  405. }
  406. ```
  407. Middlewares can be added to a router using `Router.Use()`:
  408. ```go
  409. r := mux.NewRouter()
  410. r.HandleFunc("/", handler)
  411. r.Use(loggingMiddleware)
  412. ```
  413. A more complex authentication middleware, which maps session token to users, could be written as:
  414. ```go
  415. // Define our struct
  416. type authenticationMiddleware struct {
  417. tokenUsers map[string]string
  418. }
  419. // Initialize it somewhere
  420. func (amw *authenticationMiddleware) Populate() {
  421. amw.tokenUsers["00000000"] = "user0"
  422. amw.tokenUsers["aaaaaaaa"] = "userA"
  423. amw.tokenUsers["05f717e5"] = "randomUser"
  424. amw.tokenUsers["deadbeef"] = "user0"
  425. }
  426. // Middleware function, which will be called for each request
  427. func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
  428. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  429. token := r.Header.Get("X-Session-Token")
  430. if user, found := amw.tokenUsers[token]; found {
  431. // We found the token in our map
  432. log.Printf("Authenticated user %s\n", user)
  433. // Pass down the request to the next middleware (or final handler)
  434. next.ServeHTTP(w, r)
  435. } else {
  436. // Write an error and stop the handler chain
  437. http.Error(w, "Forbidden", http.StatusForbidden)
  438. }
  439. })
  440. }
  441. ```
  442. ```go
  443. r := mux.NewRouter()
  444. r.HandleFunc("/", handler)
  445. amw := authenticationMiddleware{}
  446. amw.Populate()
  447. r.Use(amw.Middleware)
  448. ```
  449. Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. Middlewares _should_ write to `ResponseWriter` if they _are_ going to terminate the request, and they _should not_ write to `ResponseWriter` if they _are not_ going to terminate it.
  450. ### Handling CORS Requests
  451. [CORSMethodMiddleware](https://godoc.org/github.com/gorilla/mux#CORSMethodMiddleware) intends to make it easier to strictly set the `Access-Control-Allow-Methods` response header.
  452. * You will still need to use your own CORS handler to set the other CORS headers such as `Access-Control-Allow-Origin`
  453. * The middleware will set the `Access-Control-Allow-Methods` header to all the method matchers (e.g. `r.Methods(http.MethodGet, http.MethodPut, http.MethodOptions)` -> `Access-Control-Allow-Methods: GET,PUT,OPTIONS`) on a route
  454. * If you do not specify any methods, then:
  455. > _Important_: there must be an `OPTIONS` method matcher for the middleware to set the headers.
  456. Here is an example of using `CORSMethodMiddleware` along with a custom `OPTIONS` handler to set all the required CORS headers:
  457. ```go
  458. package main
  459. import (
  460. "net/http"
  461. "github.com/gorilla/mux"
  462. )
  463. func main() {
  464. r := mux.NewRouter()
  465. // IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers
  466. r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions)
  467. r.Use(mux.CORSMethodMiddleware(r))
  468. http.ListenAndServe(":8080", r)
  469. }
  470. func fooHandler(w http.ResponseWriter, r *http.Request) {
  471. w.Header().Set("Access-Control-Allow-Origin", "*")
  472. if r.Method == http.MethodOptions {
  473. return
  474. }
  475. w.Write([]byte("foo"))
  476. }
  477. ```
  478. And an request to `/foo` using something like:
  479. ```bash
  480. curl localhost:8080/foo -v
  481. ```
  482. Would look like:
  483. ```bash
  484. * Trying ::1...
  485. * TCP_NODELAY set
  486. * Connected to localhost (::1) port 8080 (#0)
  487. > GET /foo HTTP/1.1
  488. > Host: localhost:8080
  489. > User-Agent: curl/7.59.0
  490. > Accept: */*
  491. >
  492. < HTTP/1.1 200 OK
  493. < Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS
  494. < Access-Control-Allow-Origin: *
  495. < Date: Fri, 28 Jun 2019 20:13:30 GMT
  496. < Content-Length: 3
  497. < Content-Type: text/plain; charset=utf-8
  498. <
  499. * Connection #0 to host localhost left intact
  500. foo
  501. ```
  502. ### Testing Handlers
  503. Testing handlers in a Go web application is straightforward, and _mux_ doesn't complicate this any further. Given two files: `endpoints.go` and `endpoints_test.go`, here's how we'd test an application using _mux_.
  504. First, our simple HTTP handler:
  505. ```go
  506. // endpoints.go
  507. package main
  508. func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
  509. // A very simple health check.
  510. w.Header().Set("Content-Type", "application/json")
  511. w.WriteHeader(http.StatusOK)
  512. // In the future we could report back on the status of our DB, or our cache
  513. // (e.g. Redis) by performing a simple PING, and include them in the response.
  514. io.WriteString(w, `{"alive": true}`)
  515. }
  516. func main() {
  517. r := mux.NewRouter()
  518. r.HandleFunc("/health", HealthCheckHandler)
  519. log.Fatal(http.ListenAndServe("localhost:8080", r))
  520. }
  521. ```
  522. Our test code:
  523. ```go
  524. // endpoints_test.go
  525. package main
  526. import (
  527. "net/http"
  528. "net/http/httptest"
  529. "testing"
  530. )
  531. func TestHealthCheckHandler(t *testing.T) {
  532. // Create a request to pass to our handler. We don't have any query parameters for now, so we'll
  533. // pass 'nil' as the third parameter.
  534. req, err := http.NewRequest("GET", "/health", nil)
  535. if err != nil {
  536. t.Fatal(err)
  537. }
  538. // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
  539. rr := httptest.NewRecorder()
  540. handler := http.HandlerFunc(HealthCheckHandler)
  541. // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
  542. // directly and pass in our Request and ResponseRecorder.
  543. handler.ServeHTTP(rr, req)
  544. // Check the status code is what we expect.
  545. if status := rr.Code; status != http.StatusOK {
  546. t.Errorf("handler returned wrong status code: got %v want %v",
  547. status, http.StatusOK)
  548. }
  549. // Check the response body is what we expect.
  550. expected := `{"alive": true}`
  551. if rr.Body.String() != expected {
  552. t.Errorf("handler returned unexpected body: got %v want %v",
  553. rr.Body.String(), expected)
  554. }
  555. }
  556. ```
  557. In the case that our routes have [variables](#examples), we can pass those in the request. We could write
  558. [table-driven tests](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go) to test multiple
  559. possible route variables as needed.
  560. ```go
  561. // endpoints.go
  562. func main() {
  563. r := mux.NewRouter()
  564. // A route with a route variable:
  565. r.HandleFunc("/metrics/{type}", MetricsHandler)
  566. log.Fatal(http.ListenAndServe("localhost:8080", r))
  567. }
  568. ```
  569. Our test file, with a table-driven test of `routeVariables`:
  570. ```go
  571. // endpoints_test.go
  572. func TestMetricsHandler(t *testing.T) {
  573. tt := []struct{
  574. routeVariable string
  575. shouldPass bool
  576. }{
  577. {"goroutines", true},
  578. {"heap", true},
  579. {"counters", true},
  580. {"queries", true},
  581. {"adhadaeqm3k", false},
  582. }
  583. for _, tc := range tt {
  584. path := fmt.Sprintf("/metrics/%s", tc.routeVariable)
  585. req, err := http.NewRequest("GET", path, nil)
  586. if err != nil {
  587. t.Fatal(err)
  588. }
  589. rr := httptest.NewRecorder()
  590. // Need to create a router that we can pass the request through so that the vars will be added to the context
  591. router := mux.NewRouter()
  592. router.HandleFunc("/metrics/{type}", MetricsHandler)
  593. router.ServeHTTP(rr, req)
  594. // In this case, our MetricsHandler returns a non-200 response
  595. // for a route variable it doesn't know about.
  596. if rr.Code == http.StatusOK && !tc.shouldPass {
  597. t.Errorf("handler should have failed on routeVariable %s: got %v want %v",
  598. tc.routeVariable, rr.Code, http.StatusOK)
  599. }
  600. }
  601. }
  602. ```
  603. ## Full Example
  604. Here's a complete, runnable example of a small `mux` based server:
  605. ```go
  606. package main
  607. import (
  608. "net/http"
  609. "log"
  610. "github.com/gorilla/mux"
  611. )
  612. func YourHandler(w http.ResponseWriter, r *http.Request) {
  613. w.Write([]byte("Gorilla!\n"))
  614. }
  615. func main() {
  616. r := mux.NewRouter()
  617. // Routes consist of a path and a handler function.
  618. r.HandleFunc("/", YourHandler)
  619. // Bind to a port and pass our router in
  620. log.Fatal(http.ListenAndServe(":8000", r))
  621. }
  622. ```
  623. ## License
  624. BSD licensed. See the LICENSE file for details.