102 Commits

Author SHA1 Message Date
Matt Silverlock
e67b3c02c7 Remove TravisCI badge (#503) 2019-07-20 13:14:35 -07:00
Franklin Harding
7a1bf406d6 [docs] Add documentation for using mux to serve a SPA (#493)
* Add documentation for using mux to serve a SPA

* r -> router to prevent shadowing

* Expand SPA acronym

* BrowserRouter link

* Add more comments to explain how the spaHandler.ServeHTTP method works
2019-07-20 07:53:35 -07:00
Christian Muehlhaeuser
eab9c4f3d2 Simplify code (#501)
Use a single append call instead of a ranged for loop.
2019-07-20 07:49:38 -07:00
Christian Muehlhaeuser
50fbc3e7fb Avoid unnecessary conversion (#502)
No need to convert here.
2019-07-20 07:48:32 -07:00
Matt Silverlock
d83b6ffe49 Update config.yml (#495)
* Update config.yml

* Update config.yml
2019-07-01 13:26:33 -07:00
Matt Silverlock
00bdffe0f3 Update stale.yml (#494) 2019-06-29 21:17:52 -07:00
Franklin Harding
0534769016 Improve CORS Method Middleware (#477)
* More sensical CORSMethodMiddleware

* Only sets Access-Control-Allow-Methods on valid preflight requests
* Does not return after setting the Access-Control-Allow-Methods header
* Does not append OPTIONS header to Access-Control-Allow-Methods
regardless of whether there is an OPTIONS method matcher
* Adds tests for the listed behavior

* Add example for CORSMethodMiddleware

* Do not check for preflight and add documentation to the README

* Use http.MethodOptions instead of "OPTIONS"

* Add link to CORSMethodMiddleware section to readme

* Add test for unmatching route methods

* Rename CORS Method Middleware to Handling CORS Requests in README

* Link CORSMethodMiddleware in README to godoc

* Break CORSMethodMiddleware doc into bullets for readability

* Add comment about specifying OPTIONS to example in README for CORSMethodMiddleware

* Document cURL command used for testing CORS Method Middleware

* Update comment in example to "Handle the request"

* Add explicit comment about OPTIONS matchers to CORSMethodMiddleware doc

* Update circleci config to only check gofmt diff on latest go version

* Break up gofmt and go vet checks into separate steps.

* Use canonical circleci config
2019-06-29 13:52:29 -07:00
Matt Silverlock
d70f7b4baa Delete ISSUE_TEMPLATE.md (#492) 2019-06-29 11:01:59 -07:00
Franklin Harding
48f941fa99 Use subtests for middleware tests (#478)
* Use subtests for middleware tests
* Don't use subtests for MiddlewareAdd
2019-06-29 10:24:12 -07:00
Matt Silverlock
64954673e9 Delete .travis.yml (#490) 2019-06-28 16:07:30 -07:00
Franklin Harding
4248f5cd87 Fix nil panic in authentication middleware example (#489) 2019-06-28 08:33:07 -07:00
Matt Silverlock
212aa90d7c [WIP] Create CircleCI config (#484)
* [ci] Create CircleCI config
* Fix typos in container versions
* Add CircleCI badge
2019-06-24 09:05:39 -07:00
M@
ed099d4238 host:port matching does not require a :port to be specified.
In lieu of checking the template pattern on every Match request, a bool is added to the routeRegexp, and set
if the routeRegexp is a host AND there is no ":" in the template. I dislike extending the type, but I'd dislike
doing a string match on every single Match, even more.
2019-05-16 17:20:44 -07:00
sekky0905
c5c6c98bc2 [build] Remove sudo setting from travis.yml (#462) 2019-03-16 06:32:43 -07:00
Benjamin Boudreau
15a353a636 adding Router.Name to create new Route (#457) 2019-02-28 10:12:03 -08:00
Benjamin Boudreau
8eaa9f1309 fix go1.12 go vet usage (#458) 2019-02-28 09:36:07 -08:00
Souvik Haldar
8559a4f775 [docs] typo (#454) 2019-02-17 07:38:49 -08:00
moeryomenko
a7962380ca replace rr.HeaderMap by rr.Header() (#443) 2019-01-25 10:05:53 -06:00
Tim
797e653da6 Call WriteHeader after setting other header(s) in the example (#442)
From the docs: Changing the header map after a call to WriteHeader (or
Write) has no effect unless the modified headers are
trailers.
2019-01-25 05:41:49 -06:00
Gregor Weckbecker
08e7f807d3 Ignore ErrNotFound while matching Subrouters (#438)
MatchErr is set by the router to ErrNotFound if no route matches. If
no route of a Subrouter matches the error can by safely ignored. This
implementation only ignores these errors and does not ignore other
errors like ErrMethodMismatch.
2019-01-08 08:29:30 -06:00
santsai
f3ff42f93a getHost() now returns full host & port information (#383)
Previously, getHost only returned the host. As it now returns the
port as well, any .Host matches on a route will need to be updated
to also support matching on the port for cases where the port is
non default, eg: 80 for http or 443 for https.
2019-01-04 07:08:45 -08:00
tomare
ef912dd76e [bugfix] Clear matchErr when traversing subrouters.
Previously, when searching for a match, matchErr would be erroneously set, and prevent middleware from running (no match == no middleware runs).

This fix clears matchErr before traversing the next subrouter in a multi-subrouter router.
2018-12-27 16:42:16 -08:00
Raees
a31c1782bf Replace domain.com with example.com (#434)
Because domain.com is an actual business, example.com should be used for example purposes.
2018-12-25 08:41:17 -08:00
Michael Li
6137e193cd remove redundant code that remove support gorilla/context (#427)
* remove redundant code that remove support gorilla/context

* backward compatible for remove redundant code
2018-12-17 09:42:43 -05:00
Matt Silverlock
d2b5d13b92 Update and rename stale to stale.yml (#425) 2018-12-08 12:40:53 -08:00
Matt Silverlock
419fd9fe2a Add stalebot config (#424) 2018-12-07 08:41:48 -08:00
Joe Wilner
758eb64354 Improve subroute configuration propagation #422
* Pull out common shared `routeConf` so that config is pushed on to child
routers and routes.
* Removes obsolete usages of `parentRoute`
* Add tests defining compositional behavior
* Exercise `copyRouteConf` for posterity
2018-12-07 09:48:26 -06:00
kanozec
3d80bc801b Use subtests in mux_test.go (#415) 2018-10-30 08:25:28 -07:00
Nguyen Ngoc Trung (Steven)
521ea7b17d Use constant for 301 status code in regexp.go (#412) 2018-10-23 19:08:00 -07:00
Kamil Kisiel
deb579d6e0 README.md: Update site URL 2018-10-12 08:31:51 -07:00
Matt Silverlock
9e1f5955c0 Always run on the latest stable Go version. (#402)
Only run vet on the latest Go version.
2018-09-03 08:43:05 -07:00
Matt Silverlock
cf6680bc62 Create release-drafter.yml (#399) 2018-09-02 15:36:45 -07:00
Franklin Harding
8771f97498 Drop support for Go < 1.7: remove gorilla/context (#391)
* Drop support for Go < 1.7: remove gorilla/context
* Remove Go < 1.7 from Travis CI config
* Remove unneeded _native from context files
2018-09-02 15:22:40 -07:00
Shalom Yerushalmy
962c5bed07 Add 1.11 to build in travis (#398) 2018-08-30 07:23:24 -07:00
Kamil Kisiel
e48e440e4c Add test for multiple calls to Name().
Fixes #394
2018-08-07 00:52:56 -07:00
Kamil Kisiel
815b8c6a26 Clarify behaviour of Name method if called multiple times. 2018-08-07 00:50:18 -07:00
Matt Silverlock
cb4698366a Update LICENSE & AUTHORS files. (#386) 2018-06-05 14:15:56 -07:00
Jim Kalafut
e0b5abaaae Initialize user map (#371) 2018-05-26 15:17:21 -07:00
Matt Silverlock
c85619274f [deps] Add go.mod for versioned Go (#376) 2018-05-17 10:36:23 -07:00
Matt Silverlock
e3702bed27 [docs] Improve docstrings for middleware, skipclean (#375) 2018-05-12 20:22:33 -07:00
Sean Walberg
fdeb7bc314 [docs] Doc fix for testing variables in path (#374)
The example in the README does not pass the request through a mux therefore the request variables from the path are never populated. Update the sample to create a minimum viable router to use.

Fixes #373
2018-05-12 20:09:30 -07:00
Franklin Harding
5e55a4adb8 Add CORSMethodMiddleware (#366)
CORSMethodMiddleware sets the Access-Control-Allow-Methods response header
on a request, by matching routes based only on paths. It also handles
OPTIONS requests, by settings Access-Control-Allow-Methods, and then
returning without calling the next HTTP handler.
2018-05-11 18:30:14 -07:00
Matt Silverlock
ded0c29b24 Fix linter issues (docs) (#370) 2018-04-30 20:11:36 -07:00
Matt Silverlock
b57cb1605f [build] Update Go versions; add 1.10.x (#364) 2018-04-16 13:45:19 -07:00
brandon-height
94231ffd98 Fix table-driven example documentation (#363)
Prior to this change, the example documentation
found in the README.md has an errant code which
won't work in the table-driven code example.

This change modifies the variable name from `t` to `tc`
so it does not conflict with the `t *testing.T` struct
definition.

* Adds a range clause to the `for` statement
* Modifies `for` statement scope to use `tc.shouldPass`, and `tc.routeVariable`

Doc: https://github.com/gorilla/mux#testing-handlers
2018-04-03 11:23:30 -07:00
Johan Svensson
4dbd923b0c Make Use() variadic (#355)
Enables neater syntax when chaining several middleware functions.
2018-03-14 09:31:26 -07:00
Geon Kim
07ba1fd60e Modify http status code to variable in README (#350)
* Modify http status code to variable

* Modify doc

* Modify README
2018-02-25 21:11:51 -08:00
Geon Kim
d284fd8421 Modify 403 status code to const variable (#349)
* Modify http status code to variable

* Modify doc
2018-02-25 08:08:54 -08:00
Kamil Kisiel
c0091a0299 Create authentication middleware example. (#340)
* Create authentication middleware example.

For #339

* Fix example test filename.
2018-01-19 23:58:19 -08:00
Franklin Harding
0fdf828bb2 [docs] Clarify SetURLVars (#335)
* [docs] Clarify SetURLVars

Clarify in documentation that SetURLVars does not modify the given
*htttp.Request, provide an example of usage.

* Short and sweet function doc, example test.
2018-01-19 22:28:49 -08:00
Kamil Kisiel
077b44c2cf [docs] Document route.Get* methods consistently (#338)
They actually return an error instead of an empty list. `GetMethods` happened to not return an error, but it should for consistency, so I added that as well.
2018-01-19 20:51:41 -08:00
Kamil Kisiel
dc83507598 [docs] README.md: Improve "walking routes" example. (#337) (#323)
Fixes #323.

Also removed the duplicate "listing routes" example.
2018-01-19 20:47:48 -08:00
safeoy
3dbb9ed96e README.md: add miss "time" (#336) 2018-01-19 20:20:16 -08:00
Matt Silverlock
ad8790881f [docs] Fix doc.go (#333)
Addresses https://github.com/gorilla/mux/pull/294#discussion_r162309666
2018-01-18 09:53:57 -08:00
Matt Silverlock
69dae3b874 [docs] Add testing example (#331) 2018-01-16 23:16:36 -08:00
Matt Silverlock
63c5c2f1f0 [docs] Fix Middleware docs typos (#332) 2018-01-16 23:16:06 -08:00
Kamil Kisiel
85e6bfff1a Update doc.go: r.AddMiddleware(...) -> r.Use(...) 2018-01-16 17:18:53 -08:00
Kush Mansingh
0b74e3d0fe Make shutdown docs compilable (#330) 2018-01-16 14:43:47 -08:00
Roberto Santalla
53c1911da2 [feat] Add middleware support as discussed in #293 (#294)
* mux.Router now has a `Use` method that allows you to add middleware to request processing.
2018-01-16 09:23:47 -08:00
Matt Silverlock
5bbbb5b2b5 [docs] Add graceful shutdown example (#329) 2018-01-07 07:57:08 -08:00
Kamil Kisiel
512169e5d7 refactor routeRegexp, particularily newRouteRegexp. (#328)
The existing options matchPrefix, matchHost, and matchQueries are
mutually exclusive so there's no point in having a separate boolean
argument for each one. It's clearer if there's a single type variable.

strictSlash and useEncodedPath were also being passed as naked bools so
I've wrapped these in a struct called routeRegexpOptions for more clarity
at the call site.
2018-01-05 10:40:59 -08:00
Zak Chitty
5ab525f4fb Public test API to set URL params (#322)
* Add a function to set url params for test

* [docs] add justification for SetURLVars and description of alternative approach to setting url vars.
* rename SetURLParams to SetURLVars as this is more descriptive.
* rename testing to testing_helpers as this is more descriptive.

* [docs] add stipulation to SetURLVars that it should only be used for testing purposes
2017-12-08 08:08:15 -08:00
Matthew
7904d2e42e [docs] Add example usage for Route.HeadersRegexp (#320)
* Add example usage for Route.HeadersRegexp

* Improve example_route_test.go style
2017-12-04 08:11:14 -08:00
Matt Silverlock
c572efe429 [docs] Note StrictSlash re-direct behaviour #308 (#321)
* [docs] Note StrictSlash re-direct behaviour #308

* StrictSlash enabled routes return a 301 to the client
* As per the HTTP standards, non-idempotent methods, such as POST or PUT, will be followed with a GET by the client
* Users should use middleware if they wish to change this behaviour to return a HTTP 308.

* Update description of StrictSlash
2017-12-02 12:38:52 -08:00
Matt Silverlock
65ec7248c5 Create ISSUE_TEMPLATE.md (#318) 2017-11-28 16:00:09 -08:00
Matthew
4a3d4f3dd2 [bugfix] Fix method subrouter handler matching (#300) (#317)
* Test method-based subrouters for multiple matching paths

* Pass TestMethodsSubrouter

* Change http.Method* constants to string literals
- Make compatible with Go v1.5

* Make TestMethodsSubrouter stateless and concurrent

* Remove t.Run and break up tests for concurrency

* Use backticks to remove quote escaping

* Remove global method handlers and HTTP method constants
2017-11-28 11:51:17 -08:00
Chris Dostert
2d5fef06b8 [docs] fix outdated UseEncodedPath method docs (#314)
https://github.com/gorilla/mux/pull/306 changed UseEncodedPath to use native go encoded path handling so cautions in it's docs are no longer applicable.
2017-11-08 19:54:02 -08:00
Roberto Santalla
7f08801859 MatchErr is set to ErrNotFound if NotFoundHandler is used (#311) 2017-11-05 09:23:20 -08:00
Kamil Kisiel
9f48112f18 [docs] Document router.Match (#313)
* Document router.Match

The return values are getting confusing. Hopefully this helps.

* Simplify some language.

* Remove double the
2017-11-04 21:08:26 -07:00
Matt Silverlock
bc452d92e3 [build] Allow tip failures (#312)
[build] Allow tip failures
2017-11-04 13:51:27 -07:00
Kamil Kisiel
7625a85c14 .travis.yml: Remove versions < go1.5 from build matrix 2017-10-19 20:47:00 -07:00
Mike Busch
c9183aaddd use req.URL.EscapedPath() instead of getPath(req) (#306)
This change drops support of go < 1.5. go1.5 has been officially
unsupported since go1.7 was released 2016/08/15.
2017-10-19 20:46:20 -07:00
Paul B. Beskow
10490f55fa GetQueryTemplates and GetQueryRegexp extraction (#304)
Developers can now extract the query templates and regexps
from a router as lists of combined query pairs.
2017-10-19 18:19:04 -07:00
Adam Ouellette
9bd9ff2d1d Added 1.9 build step (#303) 2017-10-10 14:54:56 -07:00
Pontus Leitzler
bdd5a5a1b0 Fix WriteHeader in TestA301ResponseWriter. (#301)
WriteHeader did only set status field for a local copy that was discared
upon return.
2017-10-08 14:49:13 -07:00
Matthew Riley
3f19343c7d [docs] Document evaluation order for routes (#297) 2017-09-22 13:54:14 -07:00
Stephan Renatus
24fca303ac [docs] README.md: add missing . (#292) 2017-09-05 10:10:44 -07:00
Matt Silverlock
bb285ea687 [docs] Fix missing space in docstring (#289) 2017-08-30 13:57:41 -07:00
Mayank Patel
a659b61323 Fix #271: Return 405 instead of 404 when request method doesn't match the route 2017-08-29 22:39:17 -07:00
Chris Hines
ac112f7d75 Prefer scheme on child route when building URLs. 2017-07-04 00:43:45 -07:00
Chris Hines
37b3a6cace Use scheme from parent router when building URLs. 2017-07-04 00:43:45 -07:00
Cody Oss
8c683ee571 Fix typo 2017-06-21 15:07:33 -07:00
Chris Hines
18fca31550 Add test and fix for escaped query values.
Reproduces and fixes #238.
2017-06-02 12:31:40 -07:00
Chris Hines
c7a138dbc1 Update docs. 2017-06-02 12:31:40 -07:00
Pavel Ivanov
f9aa23a02b Add tests for support for queries in URL reversing. 2017-06-02 12:31:40 -07:00
Pavel Ivanov
9c9af153a1 Add support for queries in URL reversing. 2017-06-02 12:31:40 -07:00
Nick Hudkins
043ee6597c Update Walking Routes Section
Fixed invalid method chaining.
2017-05-23 18:01:04 -07:00
Nick Hudkins
59ce66852b Fix invalid example code
In the "List Routes" example code, `.HandleFunc` was being called on a `*mux.Route` rather than `*mux.Router`. Updated the example code to work :)
2017-05-23 18:01:04 -07:00
Brian Michel
85b8c203a4 Removing half of conflict marker (#268)
Looks like there was just part of a conflict marker in the README file, so I figured I'd remove it.
2017-05-22 19:46:13 -07:00
Nick Miyake
456bcfa82d Update README with example for Router.Walk 2017-05-22 08:17:48 -07:00
Nick Miyake
4d814f7650 Update ancestors parameter for WalkFunc for matcher subrouters
Fixes #263
2017-05-22 08:17:48 -07:00
Nick Miyake
a322b2c2ec Update Walk to match all subrouters
Matches all routes instead of just routes with paths.

Fixes #261
2017-05-21 14:35:07 -07:00
Chris Hines
bcd8bc72b0 Support building URLs with non-http schemes. (#260)
* Move misplaced tests and fix comments.

* Support building URLs with non-http schemes.

- Capture first scheme configured for a route for use when building
  URLs.
- Add new Route.URLScheme method similar to URLHost and URLPath.
- Update Route.URLHost and Route.URL to use the captured scheme if
  present.

* Remove Route.URLScheme method.

* Remove UTF-8 BOM.
2017-05-20 21:50:13 -07:00
Bulat Gaifullin
751308a60a Updated README 2017-05-20 15:55:46 -07:00
Bulat Gaifullin
b552615e22 Added method Route.GetMethods 2017-05-20 15:55:46 -07:00
Bulat Gaifullin
1856953e53 Added method Route.GetPathRegexp 2017-05-20 15:55:46 -07:00
Carlos Alexandro Becker
4c1c3952b7 fixed typo (#250) 2017-04-26 21:12:50 -07:00
Diego Siqueira
599cba5e7b Fixing Regexp in the benchmark test (#234)
Signed-off-by: DiSiqueira <dieg0@live.com>
2017-02-28 14:43:54 -08:00
Shane Smith-Sahnow
ad4ce0eb16 updating logic in route matcher, cleaner and saner (#235) 2017-02-27 19:44:49 -08:00
Kamil Kisiel
999ef73f5d Merge pull request #232 from DavidJFelix/patch-1
Add sourcegraph badge
2017-02-23 12:25:54 -08:00
David J. Felix
89d16fe9a0 Add sourcegraph badge
Fixes #228
2017-02-23 14:57:28 -05:00
Kamil Kisiel
94e7d24fd2 Add Go 1.8 to .travis.yml 2017-02-17 11:26:16 -08:00
25 changed files with 3408 additions and 732 deletions

87
.circleci/config.yml Normal file
View File

@@ -0,0 +1,87 @@
version: 2.0
jobs:
# Base test configuration for Go library tests Each distinct version should
# inherit this base, and override (at least) the container image used.
"test": &test
docker:
- image: circleci/golang:latest
working_directory: /go/src/github.com/gorilla/mux
steps: &steps
# Our build steps: we checkout the repo, fetch our deps, lint, and finally
# run "go test" on the package.
- checkout
# Logs the version in our build logs, for posterity
- run: go version
- run:
name: "Fetch dependencies"
command: >
go get -t -v ./...
# Only run gofmt, vet & lint against the latest Go version
- run:
name: "Run golint"
command: >
if [ "${LATEST}" = true ] && [ -z "${SKIP_GOLINT}" ]; then
go get -u golang.org/x/lint/golint
golint ./...
fi
- run:
name: "Run gofmt"
command: >
if [[ "${LATEST}" = true ]]; then
diff -u <(echo -n) <(gofmt -d -e .)
fi
- run:
name: "Run go vet"
command: >
if [[ "${LATEST}" = true ]]; then
go vet -v ./...
fi
- run: go test -v -race ./...
"latest":
<<: *test
environment:
LATEST: true
"1.12":
<<: *test
docker:
- image: circleci/golang:1.12
"1.11":
<<: *test
docker:
- image: circleci/golang:1.11
"1.10":
<<: *test
docker:
- image: circleci/golang:1.10
"1.9":
<<: *test
docker:
- image: circleci/golang:1.9
"1.8":
<<: *test
docker:
- image: circleci/golang:1.8
"1.7":
<<: *test
docker:
- image: circleci/golang:1.7
workflows:
version: 2
build:
jobs:
- "latest"
- "1.12"
- "1.11"
- "1.10"
- "1.9"
- "1.8"
- "1.7"

8
.github/release-drafter.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
# Config for https://github.com/apps/release-drafter
template: |
<summary of changes here>
## CHANGELOG
$CHANGES

12
.github/stale.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
daysUntilStale: 75
daysUntilClose: 14
# Issues with these labels will never be considered stale
exemptLabels:
- proposal
- needs review
- build system
staleLabel: stale
markComment: >
This issue has been automatically marked as stale because it hasn't seen
a recent update. It'll be automatically closed in a few days.
closeComment: false

View File

@@ -1,21 +0,0 @@
language: go
sudo: false
matrix:
include:
- go: 1.2
- go: 1.3
- go: 1.4
- go: 1.5
- go: 1.6
- go: 1.7
- go: tip
install:
- # Skip
script:
- go get -t -v ./...
- diff -u <(echo -n) <(gofmt -d .)
- go tool vet .
- go test -v -race ./...

8
AUTHORS Normal file
View File

@@ -0,0 +1,8 @@
# This is the official list of gorilla/mux authors for copyright purposes.
#
# Please keep the list sorted.
Google LLC (https://opensource.google.com/)
Kamil Kisielk <kamil@kamilkisiel.net>
Matt Silverlock <matt@eatsleeprepeat.net>
Rodrigo Moraes (https://github.com/moraes)

View File

@@ -1,4 +1,4 @@
Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are

618
README.md
View File

@@ -1,11 +1,12 @@
gorilla/mux
===
# gorilla/mux
[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux)
[![CircleCI](https://circleci.com/gh/gorilla/mux.svg?style=svg)](https://circleci.com/gh/gorilla/mux)
[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png)
http://www.gorillatoolkit.org/pkg/mux
https://www.gorillatoolkit.org/pkg/mux
Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to
their respective handler.
@@ -14,7 +15,7 @@ The name mux stands for "HTTP request multiplexer". Like the standard `http.Serv
* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
* URL hosts and paths can have variables with an optional regular expression.
* URL hosts, paths and query values can have variables with an optional regular expression.
* Registered URLs can be built, or "reversed", which helps maintaining references to resources.
* 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.
@@ -23,9 +24,14 @@ The name mux stands for "HTTP request multiplexer". Like the standard `http.Serv
* [Install](#install)
* [Examples](#examples)
* [Matching Routes](#matching-routes)
* [Listing Routes](#listing-routes)
* [Static Files](#static-files)
* [Serving Single Page Applications](#serving-single-page-applications) (e.g. React, Vue, Ember.js, etc.)
* [Registered URLs](#registered-urls)
* [Walking Routes](#walking-routes)
* [Graceful Shutdown](#graceful-shutdown)
* [Middleware](#middleware)
* [Handling CORS Requests](#handling-cors-requests)
* [Testing Handlers](#testing-handlers)
* [Full Example](#full-example)
---
@@ -44,11 +50,11 @@ Let's start registering a couple of URL paths and handlers:
```go
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r)
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r)
}
```
@@ -67,9 +73,9 @@ The names are used to create a map of route variables which can be retrieved cal
```go
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"])
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"])
}
```
@@ -84,7 +90,7 @@ r := mux.NewRouter()
// Only matches if domain is "www.example.com".
r.Host("www.example.com")
// Matches a dynamic subdomain.
r.Host("{subdomain:[a-z]+}.domain.com")
r.Host("{subdomain:[a-z]+}.example.com")
```
There are several other matchers that can be added. To match path prefixes:
@@ -121,7 +127,7 @@ r.Queries("key", "value")
```go
r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
return r.ProtoMajor == 0
return r.ProtoMajor == 0
})
```
@@ -134,6 +140,14 @@ r.HandleFunc("/products", ProductsHandler).
Schemes("http")
```
Routes are tested in the order they were added to the router. If two routes match, the first one wins:
```go
r := mux.NewRouter()
r.HandleFunc("/specific", specificHandler)
r.PathPrefix("/").Handler(catchAllHandler)
```
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".
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:
@@ -168,62 +182,114 @@ s.HandleFunc("/{key}/", ProductHandler)
s.HandleFunc("/{key}/details", ProductDetailsHandler)
```
### Listing Routes
Routes on a mux can be listed using the Router.Walk method—useful for generating documentation:
```go
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func handler(w http.ResponseWriter, r *http.Request) {
return
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.HandleFunc("/products", handler)
r.HandleFunc("/articles", handler)
r.HandleFunc("/articles/{id}", handler)
r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
t, err := route.GetPathTemplate()
if err != nil {
return err
}
fmt.Println(t)
return nil
})
http.Handle("/", r)
}
```
### Static Files
Note that the path provided to `PathPrefix()` represents a "wildcard": calling
`PathPrefix("/static/").Handler(...)` means that the handler will be passed any
request that matches "/static/*". This makes it easy to serve static files with mux:
request that matches "/static/\*". This makes it easy to serve static files with mux:
```go
func main() {
var dir string
var dir string
flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
flag.Parse()
r := mux.NewRouter()
flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
flag.Parse()
r := mux.NewRouter()
// This will serve files under http://localhost:8000/static/<filename>
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
// This will serve files under http://localhost:8000/static/<filename>
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
```
### Serving Single Page Applications
Most of the time it makes sense to serve your SPA on a separate web server from your API,
but sometimes it's desirable to serve them both from one place. It's possible to write a simple
handler for serving your SPA (for use with React Router's [BrowserRouter](https://reacttraining.com/react-router/web/api/BrowserRouter) for example), and leverage
mux's powerful routing for your API endpoints.
```go
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"path/filepath"
"time"
"github.com/gorilla/mux"
)
// spaHandler implements the http.Handler interface, so we can use it
// to respond to HTTP requests. The path to the static directory and
// path to the index file within that static directory are used to
// serve the SPA in the given static directory.
type spaHandler struct {
staticPath string
indexPath string
}
// ServeHTTP inspects the URL path to locate a file within the static dir
// on the SPA handler. If a file is found, it will be served. If not, the
// file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application).
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
// an example API handler
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
})
spa := spaHandler{staticPath: "build", indexPath: "index.html"}
router.PathPrefix("/").Handler(spa)
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8000",
Handler: router,
Addr: "127.0.0.1:8000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
@@ -257,19 +323,21 @@ url, err := r.Get("article").URL("category", "technology", "id", "42")
"/articles/technology/42"
```
This also works for host variables:
This also works for host and query value variables:
```go
r := mux.NewRouter()
r.Host("{subdomain}.domain.com").
r.Host("{subdomain}.example.com").
Path("/articles/{category}/{id:[0-9]+}").
Queries("filter", "{filter}").
HandlerFunc(ArticleHandler).
Name("article")
// url.String() will be "http://news.domain.com/articles/technology/42"
// url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla"
url, err := r.Get("article").URL("subdomain", "news",
"category", "technology",
"id", "42")
"id", "42",
"filter", "gorilla")
```
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.
@@ -285,7 +353,7 @@ r.HeadersRegexp("Content-Type", "application/(text|json)")
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:
```go
// "http://news.domain.com/"
// "http://news.example.com/"
host, err := r.Get("article").URLHost("subdomain", "news")
// "/articles/technology/42"
@@ -296,17 +364,415 @@ And if you use subrouters, host and path defined separately can be built as well
```go
r := mux.NewRouter()
s := r.Host("{subdomain}.domain.com").Subrouter()
s := r.Host("{subdomain}.example.com").Subrouter()
s.Path("/articles/{category}/{id:[0-9]+}").
HandlerFunc(ArticleHandler).
Name("article")
// "http://news.domain.com/articles/technology/42"
// "http://news.example.com/articles/technology/42"
url, err := r.Get("article").URL("subdomain", "news",
"category", "technology",
"id", "42")
```
### Walking Routes
The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example,
the following prints all of the registered routes:
```go
package main
import (
"fmt"
"net/http"
"strings"
"github.com/gorilla/mux"
)
func handler(w http.ResponseWriter, r *http.Request) {
return
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.HandleFunc("/products", handler).Methods("POST")
r.HandleFunc("/articles", handler).Methods("GET")
r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
r.HandleFunc("/authors", handler).Queries("surname", "{surname}")
err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
pathTemplate, err := route.GetPathTemplate()
if err == nil {
fmt.Println("ROUTE:", pathTemplate)
}
pathRegexp, err := route.GetPathRegexp()
if err == nil {
fmt.Println("Path regexp:", pathRegexp)
}
queriesTemplates, err := route.GetQueriesTemplates()
if err == nil {
fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
}
queriesRegexps, err := route.GetQueriesRegexp()
if err == nil {
fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
}
methods, err := route.GetMethods()
if err == nil {
fmt.Println("Methods:", strings.Join(methods, ","))
}
fmt.Println()
return nil
})
if err != nil {
fmt.Println(err)
}
http.Handle("/", r)
}
```
### Graceful Shutdown
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`:
```go
package main
import (
"context"
"flag"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gorilla/mux"
)
func main() {
var wait time.Duration
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")
flag.Parse()
r := mux.NewRouter()
// Add your routes as needed
srv := &http.Server{
Addr: "0.0.0.0:8080",
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r, // Pass our instance of gorilla/mux in.
}
// Run our server in a goroutine so that it doesn't block.
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Println(err)
}
}()
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
log.Println("shutting down")
os.Exit(0)
}
```
### Middleware
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.
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.
Mux middlewares are defined using the de facto standard type:
```go
type MiddlewareFunc func(http.Handler) http.Handler
```
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.
A very basic middleware which logs the URI of the request being handled could be written as:
```go
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Println(r.RequestURI)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
```
Middlewares can be added to a router using `Router.Use()`:
```go
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(loggingMiddleware)
```
A more complex authentication middleware, which maps session token to users, could be written as:
```go
// Define our struct
type authenticationMiddleware struct {
tokenUsers map[string]string
}
// Initialize it somewhere
func (amw *authenticationMiddleware) Populate() {
amw.tokenUsers["00000000"] = "user0"
amw.tokenUsers["aaaaaaaa"] = "userA"
amw.tokenUsers["05f717e5"] = "randomUser"
amw.tokenUsers["deadbeef"] = "user0"
}
// Middleware function, which will be called for each request
func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("X-Session-Token")
if user, found := amw.tokenUsers[token]; found {
// We found the token in our map
log.Printf("Authenticated user %s\n", user)
// Pass down the request to the next middleware (or final handler)
next.ServeHTTP(w, r)
} else {
// Write an error and stop the handler chain
http.Error(w, "Forbidden", http.StatusForbidden)
}
})
}
```
```go
r := mux.NewRouter()
r.HandleFunc("/", handler)
amw := authenticationMiddleware{}
amw.Populate()
r.Use(amw.Middleware)
```
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.
### Handling CORS Requests
[CORSMethodMiddleware](https://godoc.org/github.com/gorilla/mux#CORSMethodMiddleware) intends to make it easier to strictly set the `Access-Control-Allow-Methods` response header.
* You will still need to use your own CORS handler to set the other CORS headers such as `Access-Control-Allow-Origin`
* 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
* If you do not specify any methods, then:
> _Important_: there must be an `OPTIONS` method matcher for the middleware to set the headers.
Here is an example of using `CORSMethodMiddleware` along with a custom `OPTIONS` handler to set all the required CORS headers:
```go
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
// IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers
r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions)
r.Use(mux.CORSMethodMiddleware(r))
http.ListenAndServe(":8080", r)
}
func fooHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodOptions {
return
}
w.Write([]byte("foo"))
}
```
And an request to `/foo` using something like:
```bash
curl localhost:8080/foo -v
```
Would look like:
```bash
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /foo HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.59.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS
< Access-Control-Allow-Origin: *
< Date: Fri, 28 Jun 2019 20:13:30 GMT
< Content-Length: 3
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
foo
```
### Testing Handlers
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_.
First, our simple HTTP handler:
```go
// endpoints.go
package main
func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
// A very simple health check.
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
// In the future we could report back on the status of our DB, or our cache
// (e.g. Redis) by performing a simple PING, and include them in the response.
io.WriteString(w, `{"alive": true}`)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/health", HealthCheckHandler)
log.Fatal(http.ListenAndServe("localhost:8080", r))
}
```
Our test code:
```go
// endpoints_test.go
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHealthCheckHandler(t *testing.T) {
// Create a request to pass to our handler. We don't have any query parameters for now, so we'll
// pass 'nil' as the third parameter.
req, err := http.NewRequest("GET", "/health", nil)
if err != nil {
t.Fatal(err)
}
// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
rr := httptest.NewRecorder()
handler := http.HandlerFunc(HealthCheckHandler)
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
// Check the status code is what we expect.
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
// Check the response body is what we expect.
expected := `{"alive": true}`
if rr.Body.String() != expected {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), expected)
}
}
```
In the case that our routes have [variables](#examples), we can pass those in the request. We could write
[table-driven tests](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go) to test multiple
possible route variables as needed.
```go
// endpoints.go
func main() {
r := mux.NewRouter()
// A route with a route variable:
r.HandleFunc("/metrics/{type}", MetricsHandler)
log.Fatal(http.ListenAndServe("localhost:8080", r))
}
```
Our test file, with a table-driven test of `routeVariables`:
```go
// endpoints_test.go
func TestMetricsHandler(t *testing.T) {
tt := []struct{
routeVariable string
shouldPass bool
}{
{"goroutines", true},
{"heap", true},
{"counters", true},
{"queries", true},
{"adhadaeqm3k", false},
}
for _, tc := range tt {
path := fmt.Sprintf("/metrics/%s", tc.routeVariable)
req, err := http.NewRequest("GET", path, nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
// Need to create a router that we can pass the request through so that the vars will be added to the context
router := mux.NewRouter()
router.HandleFunc("/metrics/{type}", MetricsHandler)
router.ServeHTTP(rr, req)
// In this case, our MetricsHandler returns a non-200 response
// for a route variable it doesn't know about.
if rr.Code == http.StatusOK && !tc.shouldPass {
t.Errorf("handler should have failed on routeVariable %s: got %v want %v",
tc.routeVariable, rr.Code, http.StatusOK)
}
}
}
```
## Full Example
Here's a complete, runnable example of a small `mux` based server:
@@ -315,22 +781,22 @@ Here's a complete, runnable example of a small `mux` based server:
package main
import (
"net/http"
"log"
"github.com/gorilla/mux"
"net/http"
"log"
"github.com/gorilla/mux"
)
func YourHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Gorilla!\n"))
w.Write([]byte("Gorilla!\n"))
}
func main() {
r := mux.NewRouter()
// Routes consist of a path and a handler function.
r.HandleFunc("/", YourHandler)
r := mux.NewRouter()
// Routes consist of a path and a handler function.
r.HandleFunc("/", YourHandler)
// Bind to a port and pass our router in
log.Fatal(http.ListenAndServe(":8000", r))
// Bind to a port and pass our router in
log.Fatal(http.ListenAndServe(":8000", r))
}
```

View File

@@ -24,7 +24,7 @@ func BenchmarkMux(b *testing.B) {
func BenchmarkMuxAlternativeInRegexp(b *testing.B) {
router := new(Router)
handler := func(w http.ResponseWriter, r *http.Request) {}
router.HandleFunc("/v1/{v1:(a|b)}", handler)
router.HandleFunc("/v1/{v1:(?:a|b)}", handler)
requestA, _ := http.NewRequest("GET", "/v1/a", nil)
requestB, _ := http.NewRequest("GET", "/v1/b", nil)

View File

@@ -1,5 +1,3 @@
// +build go1.7
package mux
import (
@@ -18,7 +16,3 @@ func contextSet(r *http.Request, key, val interface{}) *http.Request {
return r.WithContext(context.WithValue(r.Context(), key, val))
}
func contextClear(r *http.Request) {
return
}

View File

@@ -1,26 +0,0 @@
// +build !go1.7
package mux
import (
"net/http"
"github.com/gorilla/context"
)
func contextGet(r *http.Request, key interface{}) interface{} {
return context.Get(r, key)
}
func contextSet(r *http.Request, key, val interface{}) *http.Request {
if val == nil {
return r
}
context.Set(r, key, val)
return r
}
func contextClear(r *http.Request) {
context.Clear(r)
}

View File

@@ -1,40 +0,0 @@
// +build !go1.7
package mux
import (
"net/http"
"testing"
"github.com/gorilla/context"
)
// Tests that the context is cleared or not cleared properly depending on
// the configuration of the router
func TestKeepContext(t *testing.T) {
func1 := func(w http.ResponseWriter, r *http.Request) {}
r := NewRouter()
r.HandleFunc("/", func1).Name("func1")
req, _ := http.NewRequest("GET", "http://localhost/", nil)
context.Set(req, "t", 1)
res := new(http.ResponseWriter)
r.ServeHTTP(*res, req)
if _, ok := context.GetOk(req, "t"); ok {
t.Error("Context should have been cleared at end of request")
}
r.KeepContext = true
req, _ = http.NewRequest("GET", "http://localhost/", nil)
context.Set(req, "t", 1)
r.ServeHTTP(*res, req)
if _, ok := context.GetOk(req, "t"); !ok {
t.Error("Context should NOT have been cleared at end of request")
}
}

View File

@@ -1,5 +1,3 @@
// +build go1.7
package mux
import (

76
doc.go
View File

@@ -12,8 +12,8 @@ or other conditions. The main features are:
* Requests can be matched based on URL host, path, path prefix, schemes,
header and query values, HTTP methods or using custom matchers.
* URL hosts and paths can have variables with an optional regular
expression.
* URL hosts, paths and query values can have variables with an optional
regular expression.
* Registered URLs can be built, or "reversed", which helps maintaining
references to resources.
* Routes can be used as subrouters: nested routes are only tested if the
@@ -188,18 +188,20 @@ key/value pairs for the route variables. For the previous route, we would do:
"/articles/technology/42"
This also works for host variables:
This also works for host and query value variables:
r := mux.NewRouter()
r.Host("{subdomain}.domain.com").
Path("/articles/{category}/{id:[0-9]+}").
Queries("filter", "{filter}").
HandlerFunc(ArticleHandler).
Name("article")
// url.String() will be "http://news.domain.com/articles/technology/42"
// url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
url, err := r.Get("article").URL("subdomain", "news",
"category", "technology",
"id", "42")
"id", "42",
"filter", "gorilla")
All variables defined in the route are required, and their values must
conform to the corresponding patterns. These requirements guarantee that a
@@ -236,5 +238,69 @@ as well:
url, err := r.Get("article").URL("subdomain", "news",
"category", "technology",
"id", "42")
Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. 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.
type MiddlewareFunc func(http.Handler) http.Handler
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 (closures can access variables from the context where they are created).
A very basic middleware which logs the URI of the request being handled could be written as:
func simpleMw(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Println(r.RequestURI)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
Middlewares can be added to a router using `Router.Use()`:
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(simpleMw)
A more complex authentication middleware, which maps session token to users, could be written as:
// Define our struct
type authenticationMiddleware struct {
tokenUsers map[string]string
}
// Initialize it somewhere
func (amw *authenticationMiddleware) Populate() {
amw.tokenUsers["00000000"] = "user0"
amw.tokenUsers["aaaaaaaa"] = "userA"
amw.tokenUsers["05f717e5"] = "randomUser"
amw.tokenUsers["deadbeef"] = "user0"
}
// Middleware function, which will be called for each request
func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("X-Session-Token")
if user, found := amw.tokenUsers[token]; found {
// We found the token in our map
log.Printf("Authenticated user %s\n", user)
next.ServeHTTP(w, r)
} else {
http.Error(w, "Forbidden", http.StatusForbidden)
}
})
}
r := mux.NewRouter()
r.HandleFunc("/", handler)
amw := authenticationMiddleware{tokenUsers: make(map[string]string)}
amw.Populate()
r.Use(amw.Middleware)
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.
*/
package mux

View File

@@ -0,0 +1,46 @@
package mux_test
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
// Define our struct
type authenticationMiddleware struct {
tokenUsers map[string]string
}
// Initialize it somewhere
func (amw *authenticationMiddleware) Populate() {
amw.tokenUsers["00000000"] = "user0"
amw.tokenUsers["aaaaaaaa"] = "userA"
amw.tokenUsers["05f717e5"] = "randomUser"
amw.tokenUsers["deadbeef"] = "user0"
}
// Middleware function, which will be called for each request
func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("X-Session-Token")
if user, found := amw.tokenUsers[token]; found {
// We found the token in our map
log.Printf("Authenticated user %s\n", user)
next.ServeHTTP(w, r)
} else {
http.Error(w, "Forbidden", http.StatusForbidden)
}
})
}
func Example_authenticationMiddleware() {
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Do something here
})
amw := authenticationMiddleware{make(map[string]string)}
amw.Populate()
r.Use(amw.Middleware)
}

View File

@@ -0,0 +1,37 @@
package mux_test
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/gorilla/mux"
)
func ExampleCORSMethodMiddleware() {
r := mux.NewRouter()
r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
// Handle the request
}).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "http://example.com")
w.Header().Set("Access-Control-Max-Age", "86400")
}).Methods(http.MethodOptions)
r.Use(mux.CORSMethodMiddleware(r))
rw := httptest.NewRecorder()
req, _ := http.NewRequest("OPTIONS", "/foo", nil) // needs to be OPTIONS
req.Header.Set("Access-Control-Request-Method", "POST") // needs to be non-empty
req.Header.Set("Access-Control-Request-Headers", "Authorization") // needs to be non-empty
req.Header.Set("Origin", "http://example.com") // needs to be non-empty
r.ServeHTTP(rw, req)
fmt.Println(rw.Header().Get("Access-Control-Allow-Methods"))
fmt.Println(rw.Header().Get("Access-Control-Allow-Origin"))
// Output:
// GET,PUT,PATCH,OPTIONS
// http://example.com
}

51
example_route_test.go Normal file
View File

@@ -0,0 +1,51 @@
package mux_test
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
// This example demonstrates setting a regular expression matcher for
// the header value. A plain word will match any value that contains a
// matching substring as if the pattern was wrapped with `.*`.
func ExampleRoute_HeadersRegexp() {
r := mux.NewRouter()
route := r.NewRoute().HeadersRegexp("Accept", "html")
req1, _ := http.NewRequest("GET", "example.com", nil)
req1.Header.Add("Accept", "text/plain")
req1.Header.Add("Accept", "text/html")
req2, _ := http.NewRequest("GET", "example.com", nil)
req2.Header.Set("Accept", "application/xhtml+xml")
matchInfo := &mux.RouteMatch{}
fmt.Printf("Match: %v %q\n", route.Match(req1, matchInfo), req1.Header["Accept"])
fmt.Printf("Match: %v %q\n", route.Match(req2, matchInfo), req2.Header["Accept"])
// Output:
// Match: true ["text/plain" "text/html"]
// Match: true ["application/xhtml+xml"]
}
// This example demonstrates setting a strict regular expression matcher
// for the header value. Using the start and end of string anchors, the
// value must be an exact match.
func ExampleRoute_HeadersRegexp_exactMatch() {
r := mux.NewRouter()
route := r.NewRoute().HeadersRegexp("Origin", "^https://example.co$")
yes, _ := http.NewRequest("GET", "example.co", nil)
yes.Header.Set("Origin", "https://example.co")
no, _ := http.NewRequest("GET", "example.co.uk", nil)
no.Header.Set("Origin", "https://example.co.uk")
matchInfo := &mux.RouteMatch{}
fmt.Printf("Match: %v %q\n", route.Match(yes, matchInfo), yes.Header["Origin"])
fmt.Printf("Match: %v %q\n", route.Match(no, matchInfo), no.Header["Origin"])
// Output:
// Match: true ["https://example.co"]
// Match: false ["https://example.co.uk"]
}

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/gorilla/mux
go 1.12

79
middleware.go Normal file
View File

@@ -0,0 +1,79 @@
package mux
import (
"net/http"
"strings"
)
// MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler.
// 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.
type MiddlewareFunc func(http.Handler) http.Handler
// middleware interface is anything which implements a MiddlewareFunc named Middleware.
type middleware interface {
Middleware(handler http.Handler) http.Handler
}
// Middleware allows MiddlewareFunc to implement the middleware interface.
func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler {
return mw(handler)
}
// Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.
func (r *Router) Use(mwf ...MiddlewareFunc) {
for _, fn := range mwf {
r.middlewares = append(r.middlewares, fn)
}
}
// useInterface appends a middleware to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.
func (r *Router) useInterface(mw middleware) {
r.middlewares = append(r.middlewares, mw)
}
// CORSMethodMiddleware automatically sets the Access-Control-Allow-Methods response header
// on requests for routes that have an OPTIONS method matcher to all the method matchers on
// the route. Routes that do not explicitly handle OPTIONS requests will not be processed
// by the middleware. See examples for usage.
func CORSMethodMiddleware(r *Router) MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
allMethods, err := getAllMethodsForRoute(r, req)
if err == nil {
for _, v := range allMethods {
if v == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", strings.Join(allMethods, ","))
}
}
}
next.ServeHTTP(w, req)
})
}
}
// getAllMethodsForRoute returns all the methods from method matchers matching a given
// request.
func getAllMethodsForRoute(r *Router, req *http.Request) ([]string, error) {
var allMethods []string
err := r.Walk(func(route *Route, _ *Router, _ []*Route) error {
for _, m := range route.matchers {
if _, ok := m.(*routeRegexp); ok {
if m.Match(req, &RouteMatch{}) {
methods, err := route.GetMethods()
if err != nil {
return err
}
allMethods = append(allMethods, methods...)
}
break
}
}
return nil
})
return allMethods, err
}

545
middleware_test.go Normal file
View File

@@ -0,0 +1,545 @@
package mux
import (
"bytes"
"net/http"
"testing"
)
type testMiddleware struct {
timesCalled uint
}
func (tm *testMiddleware) Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tm.timesCalled++
h.ServeHTTP(w, r)
})
}
func dummyHandler(w http.ResponseWriter, r *http.Request) {}
func TestMiddlewareAdd(t *testing.T) {
router := NewRouter()
router.HandleFunc("/", dummyHandler).Methods("GET")
mw := &testMiddleware{}
router.useInterface(mw)
if len(router.middlewares) != 1 || router.middlewares[0] != mw {
t.Fatal("Middleware interface was not added correctly")
}
router.Use(mw.Middleware)
if len(router.middlewares) != 2 {
t.Fatal("Middleware method was not added correctly")
}
banalMw := func(handler http.Handler) http.Handler {
return handler
}
router.Use(banalMw)
if len(router.middlewares) != 3 {
t.Fatal("Middleware function was not added correctly")
}
}
func TestMiddleware(t *testing.T) {
router := NewRouter()
router.HandleFunc("/", dummyHandler).Methods("GET")
mw := &testMiddleware{}
router.useInterface(mw)
rw := NewRecorder()
req := newRequest("GET", "/")
t.Run("regular middleware call", func(t *testing.T) {
router.ServeHTTP(rw, req)
if mw.timesCalled != 1 {
t.Fatalf("Expected %d calls, but got only %d", 1, mw.timesCalled)
}
})
t.Run("not called for 404", func(t *testing.T) {
req = newRequest("GET", "/not/found")
router.ServeHTTP(rw, req)
if mw.timesCalled != 1 {
t.Fatalf("Expected %d calls, but got only %d", 1, mw.timesCalled)
}
})
t.Run("not called for method mismatch", func(t *testing.T) {
req = newRequest("POST", "/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 1 {
t.Fatalf("Expected %d calls, but got only %d", 1, mw.timesCalled)
}
})
t.Run("regular call using function middleware", func(t *testing.T) {
router.Use(mw.Middleware)
req = newRequest("GET", "/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 3 {
t.Fatalf("Expected %d calls, but got only %d", 3, mw.timesCalled)
}
})
}
func TestMiddlewareSubrouter(t *testing.T) {
router := NewRouter()
router.HandleFunc("/", dummyHandler).Methods("GET")
subrouter := router.PathPrefix("/sub").Subrouter()
subrouter.HandleFunc("/x", dummyHandler).Methods("GET")
mw := &testMiddleware{}
subrouter.useInterface(mw)
rw := NewRecorder()
req := newRequest("GET", "/")
t.Run("not called for route outside subrouter", func(t *testing.T) {
router.ServeHTTP(rw, req)
if mw.timesCalled != 0 {
t.Fatalf("Expected %d calls, but got only %d", 0, mw.timesCalled)
}
})
t.Run("not called for subrouter root 404", func(t *testing.T) {
req = newRequest("GET", "/sub/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 0 {
t.Fatalf("Expected %d calls, but got only %d", 0, mw.timesCalled)
}
})
t.Run("called once for route inside subrouter", func(t *testing.T) {
req = newRequest("GET", "/sub/x")
router.ServeHTTP(rw, req)
if mw.timesCalled != 1 {
t.Fatalf("Expected %d calls, but got only %d", 1, mw.timesCalled)
}
})
t.Run("not called for 404 inside subrouter", func(t *testing.T) {
req = newRequest("GET", "/sub/not/found")
router.ServeHTTP(rw, req)
if mw.timesCalled != 1 {
t.Fatalf("Expected %d calls, but got only %d", 1, mw.timesCalled)
}
})
t.Run("middleware added to router", func(t *testing.T) {
router.useInterface(mw)
t.Run("called once for route outside subrouter", func(t *testing.T) {
req = newRequest("GET", "/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 2 {
t.Fatalf("Expected %d calls, but got only %d", 2, mw.timesCalled)
}
})
t.Run("called twice for route inside subrouter", func(t *testing.T) {
req = newRequest("GET", "/sub/x")
router.ServeHTTP(rw, req)
if mw.timesCalled != 4 {
t.Fatalf("Expected %d calls, but got only %d", 4, mw.timesCalled)
}
})
})
}
func TestMiddlewareExecution(t *testing.T) {
mwStr := []byte("Middleware\n")
handlerStr := []byte("Logic\n")
router := NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, e *http.Request) {
w.Write(handlerStr)
})
t.Run("responds normally without middleware", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/")
router.ServeHTTP(rw, req)
if !bytes.Equal(rw.Body.Bytes(), handlerStr) {
t.Fatal("Handler response is not what it should be")
}
})
t.Run("responds with handler and middleware response", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/")
router.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(mwStr)
h.ServeHTTP(w, r)
})
})
router.ServeHTTP(rw, req)
if !bytes.Equal(rw.Body.Bytes(), append(mwStr, handlerStr...)) {
t.Fatal("Middleware + handler response is not what it should be")
}
})
}
func TestMiddlewareNotFound(t *testing.T) {
mwStr := []byte("Middleware\n")
handlerStr := []byte("Logic\n")
router := NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, e *http.Request) {
w.Write(handlerStr)
})
router.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(mwStr)
h.ServeHTTP(w, r)
})
})
// Test not found call with default handler
t.Run("not called", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/notfound")
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a 404")
}
})
t.Run("not called with custom not found handler", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/notfound")
router.NotFoundHandler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("Custom 404 handler"))
})
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a custom 404")
}
})
}
func TestMiddlewareMethodMismatch(t *testing.T) {
mwStr := []byte("Middleware\n")
handlerStr := []byte("Logic\n")
router := NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, e *http.Request) {
w.Write(handlerStr)
}).Methods("GET")
router.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(mwStr)
h.ServeHTTP(w, r)
})
})
t.Run("not called", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("POST", "/")
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a method mismatch")
}
})
t.Run("not called with custom method not allowed handler", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("POST", "/")
router.MethodNotAllowedHandler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("Method not allowed"))
})
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a method mismatch")
}
})
}
func TestMiddlewareNotFoundSubrouter(t *testing.T) {
mwStr := []byte("Middleware\n")
handlerStr := []byte("Logic\n")
router := NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, e *http.Request) {
w.Write(handlerStr)
})
subrouter := router.PathPrefix("/sub/").Subrouter()
subrouter.HandleFunc("/", func(w http.ResponseWriter, e *http.Request) {
w.Write(handlerStr)
})
router.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(mwStr)
h.ServeHTTP(w, r)
})
})
t.Run("not called", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/sub/notfound")
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a 404")
}
})
t.Run("not called with custom not found handler", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/sub/notfound")
subrouter.NotFoundHandler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("Custom 404 handler"))
})
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a custom 404")
}
})
}
func TestMiddlewareMethodMismatchSubrouter(t *testing.T) {
mwStr := []byte("Middleware\n")
handlerStr := []byte("Logic\n")
router := NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, e *http.Request) {
w.Write(handlerStr)
})
subrouter := router.PathPrefix("/sub/").Subrouter()
subrouter.HandleFunc("/", func(w http.ResponseWriter, e *http.Request) {
w.Write(handlerStr)
}).Methods("GET")
router.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(mwStr)
h.ServeHTTP(w, r)
})
})
t.Run("not called", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("POST", "/sub/")
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a method mismatch")
}
})
t.Run("not called with custom method not allowed handler", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("POST", "/sub/")
router.MethodNotAllowedHandler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("Method not allowed"))
})
router.ServeHTTP(rw, req)
if bytes.Contains(rw.Body.Bytes(), mwStr) {
t.Fatal("Middleware was called for a method mismatch")
}
})
}
func TestCORSMethodMiddleware(t *testing.T) {
testCases := []struct {
name string
registerRoutes func(r *Router)
requestHeader http.Header
requestMethod string
requestPath string
expectedAccessControlAllowMethodsHeader string
expectedResponse string
}{
{
name: "does not set without OPTIONS matcher",
registerRoutes: func(r *Router) {
r.HandleFunc("/foo", stringHandler("a")).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
},
requestMethod: "GET",
requestPath: "/foo",
expectedAccessControlAllowMethodsHeader: "",
expectedResponse: "a",
},
{
name: "sets on non OPTIONS",
registerRoutes: func(r *Router) {
r.HandleFunc("/foo", stringHandler("a")).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
r.HandleFunc("/foo", stringHandler("b")).Methods(http.MethodOptions)
},
requestMethod: "GET",
requestPath: "/foo",
expectedAccessControlAllowMethodsHeader: "GET,PUT,PATCH,OPTIONS",
expectedResponse: "a",
},
{
name: "sets without preflight headers",
registerRoutes: func(r *Router) {
r.HandleFunc("/foo", stringHandler("a")).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
r.HandleFunc("/foo", stringHandler("b")).Methods(http.MethodOptions)
},
requestMethod: "OPTIONS",
requestPath: "/foo",
expectedAccessControlAllowMethodsHeader: "GET,PUT,PATCH,OPTIONS",
expectedResponse: "b",
},
{
name: "does not set on error",
registerRoutes: func(r *Router) {
r.HandleFunc("/foo", stringHandler("a"))
},
requestMethod: "OPTIONS",
requestPath: "/foo",
expectedAccessControlAllowMethodsHeader: "",
expectedResponse: "a",
},
{
name: "sets header on valid preflight",
registerRoutes: func(r *Router) {
r.HandleFunc("/foo", stringHandler("a")).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
r.HandleFunc("/foo", stringHandler("b")).Methods(http.MethodOptions)
},
requestMethod: "OPTIONS",
requestPath: "/foo",
requestHeader: http.Header{
"Access-Control-Request-Method": []string{"GET"},
"Access-Control-Request-Headers": []string{"Authorization"},
"Origin": []string{"http://example.com"},
},
expectedAccessControlAllowMethodsHeader: "GET,PUT,PATCH,OPTIONS",
expectedResponse: "b",
},
{
name: "does not set methods from unmatching routes",
registerRoutes: func(r *Router) {
r.HandleFunc("/foo", stringHandler("c")).Methods(http.MethodDelete)
r.HandleFunc("/foo/bar", stringHandler("a")).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
r.HandleFunc("/foo/bar", stringHandler("b")).Methods(http.MethodOptions)
},
requestMethod: "OPTIONS",
requestPath: "/foo/bar",
requestHeader: http.Header{
"Access-Control-Request-Method": []string{"GET"},
"Access-Control-Request-Headers": []string{"Authorization"},
"Origin": []string{"http://example.com"},
},
expectedAccessControlAllowMethodsHeader: "GET,PUT,PATCH,OPTIONS",
expectedResponse: "b",
},
}
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
router := NewRouter()
tt.registerRoutes(router)
router.Use(CORSMethodMiddleware(router))
rw := NewRecorder()
req := newRequest(tt.requestMethod, tt.requestPath)
req.Header = tt.requestHeader
router.ServeHTTP(rw, req)
actualMethodsHeader := rw.Header().Get("Access-Control-Allow-Methods")
if actualMethodsHeader != tt.expectedAccessControlAllowMethodsHeader {
t.Fatalf("Expected Access-Control-Allow-Methods to equal %s but got %s", tt.expectedAccessControlAllowMethodsHeader, actualMethodsHeader)
}
actualResponse := rw.Body.String()
if actualResponse != tt.expectedResponse {
t.Fatalf("Expected response to equal %s but got %s", tt.expectedResponse, actualResponse)
}
})
}
}
func TestMiddlewareOnMultiSubrouter(t *testing.T) {
first := "first"
second := "second"
notFound := "404 not found"
router := NewRouter()
firstSubRouter := router.PathPrefix("/").Subrouter()
secondSubRouter := router.PathPrefix("/").Subrouter()
router.NotFoundHandler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte(notFound))
})
firstSubRouter.HandleFunc("/first", func(w http.ResponseWriter, r *http.Request) {
})
secondSubRouter.HandleFunc("/second", func(w http.ResponseWriter, r *http.Request) {
})
firstSubRouter.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(first))
h.ServeHTTP(w, r)
})
})
secondSubRouter.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(second))
h.ServeHTTP(w, r)
})
})
t.Run("/first uses first middleware", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/first")
router.ServeHTTP(rw, req)
if rw.Body.String() != first {
t.Fatalf("Middleware did not run: expected %s middleware to write a response (got %s)", first, rw.Body.String())
}
})
t.Run("/second uses second middleware", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/second")
router.ServeHTTP(rw, req)
if rw.Body.String() != second {
t.Fatalf("Middleware did not run: expected %s middleware to write a response (got %s)", second, rw.Body.String())
}
})
t.Run("uses not found handler", func(t *testing.T) {
rw := NewRecorder()
req := newRequest("GET", "/second/not-exist")
router.ServeHTTP(rw, req)
if rw.Body.String() != notFound {
t.Fatalf("Notfound handler did not run: expected %s for not-exist, (got %s)", notFound, rw.Body.String())
}
})
}

227
mux.go
View File

@@ -10,12 +10,19 @@ import (
"net/http"
"path"
"regexp"
"strings"
)
var (
// ErrMethodMismatch is returned when the method in the request does not match
// the method defined against the route.
ErrMethodMismatch = errors.New("method is not allowed")
// ErrNotFound is returned when no route match is found.
ErrNotFound = errors.New("no matching route was found")
)
// NewRouter returns a new router instance.
func NewRouter() *Router {
return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
return &Router{namedRoutes: make(map[string]*Route)}
}
// Router registers routes to be matched and dispatches a handler.
@@ -39,37 +46,123 @@ func NewRouter() *Router {
type Router struct {
// Configurable Handler to be used when no route matches.
NotFoundHandler http.Handler
// Parent route, if this is a subrouter.
parent parentRoute
// Configurable Handler to be used when the request method does not match the route.
MethodNotAllowedHandler http.Handler
// Routes to be matched, in order.
routes []*Route
// Routes by name for URL building.
namedRoutes map[string]*Route
// See Router.StrictSlash(). This defines the flag for new routes.
strictSlash bool
// See Router.SkipClean(). This defines the flag for new routes.
skipClean bool
// If true, do not clear the request context after handling the request.
// This has no effect when go1.7+ is used, since the context is stored
//
// Deprecated: No effect when go1.7+ is used, since the context is stored
// on the request itself.
KeepContext bool
// see Router.UseEncodedPath(). This defines a flag for all routes.
useEncodedPath bool
// Slice of middlewares to be called after a match is found
middlewares []middleware
// configuration shared with `Route`
routeConf
}
// Match matches registered routes against the request.
// common route configuration shared between `Router` and `Route`
type routeConf struct {
// If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
useEncodedPath bool
// If true, when the path pattern is "/path/", accessing "/path" will
// redirect to the former and vice versa.
strictSlash bool
// If true, when the path pattern is "/path//to", accessing "/path//to"
// will not redirect
skipClean bool
// Manager for the variables from host and path.
regexp routeRegexpGroup
// List of matchers.
matchers []matcher
// The scheme used when building URLs.
buildScheme string
buildVarsFunc BuildVarsFunc
}
// returns an effective deep copy of `routeConf`
func copyRouteConf(r routeConf) routeConf {
c := r
if r.regexp.path != nil {
c.regexp.path = copyRouteRegexp(r.regexp.path)
}
if r.regexp.host != nil {
c.regexp.host = copyRouteRegexp(r.regexp.host)
}
c.regexp.queries = make([]*routeRegexp, 0, len(r.regexp.queries))
for _, q := range r.regexp.queries {
c.regexp.queries = append(c.regexp.queries, copyRouteRegexp(q))
}
c.matchers = make([]matcher, len(r.matchers))
copy(c.matchers, r.matchers)
return c
}
func copyRouteRegexp(r *routeRegexp) *routeRegexp {
c := *r
return &c
}
// Match attempts to match the given request against the router's registered routes.
//
// If the request matches a route of this router or one of its subrouters the Route,
// Handler, and Vars fields of the the match argument are filled and this function
// returns true.
//
// If the request does not match any of this router's or its subrouters' routes
// then this function returns false. If available, a reason for the match failure
// will be filled in the match argument's MatchErr field. If the match failure type
// (eg: not found) has a registered handler, the handler is assigned to the Handler
// field of the match argument.
func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
for _, route := range r.routes {
if route.Match(req, match) {
// Build middleware chain if no error was found
if match.MatchErr == nil {
for i := len(r.middlewares) - 1; i >= 0; i-- {
match.Handler = r.middlewares[i].Middleware(match.Handler)
}
}
return true
}
}
if match.MatchErr == ErrMethodMismatch {
if r.MethodNotAllowedHandler != nil {
match.Handler = r.MethodNotAllowedHandler
return true
}
return false
}
// Closest match for a router (includes sub-routers)
if r.NotFoundHandler != nil {
match.Handler = r.NotFoundHandler
match.MatchErr = ErrNotFound
return true
}
match.MatchErr = ErrNotFound
return false
}
@@ -81,7 +174,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if !r.skipClean {
path := req.URL.Path
if r.useEncodedPath {
path = getPath(req)
path = req.URL.EscapedPath()
}
// Clean path to canonical form and redirect.
if p := cleanPath(path); p != path {
@@ -105,36 +198,44 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
req = setVars(req, match.Vars)
req = setCurrentRoute(req, match.Route)
}
if handler == nil && match.MatchErr == ErrMethodMismatch {
handler = methodNotAllowedHandler()
}
if handler == nil {
handler = http.NotFoundHandler()
}
if !r.KeepContext {
defer contextClear(req)
}
handler.ServeHTTP(w, req)
}
// Get returns a route registered with the given name.
func (r *Router) Get(name string) *Route {
return r.getNamedRoutes()[name]
return r.namedRoutes[name]
}
// GetRoute returns a route registered with the given name. This method
// was renamed to Get() and remains here for backwards compatibility.
func (r *Router) GetRoute(name string) *Route {
return r.getNamedRoutes()[name]
return r.namedRoutes[name]
}
// StrictSlash defines the trailing slash behavior for new routes. The initial
// value is false.
//
// When true, if the route path is "/path/", accessing "/path" will redirect
// When true, if the route path is "/path/", accessing "/path" will perform a redirect
// to the former and vice versa. In other words, your application will always
// see the path as specified in the route.
//
// When false, if the route path is "/path", accessing "/path/" will not match
// this route and vice versa.
//
// The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for
// routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed
// request will be made as a GET by most clients. Use middleware or client settings
// to modify this behaviour as needed.
//
// Special case: when a route sets a path prefix using the PathPrefix() method,
// strict slash is ignored for that route because the redirect behavior can't
// be determined from a prefix alone. However, any subrouters created from that
@@ -160,10 +261,6 @@ func (r *Router) SkipClean(value bool) *Router {
// UseEncodedPath tells the router to match the encoded original path
// to the routes.
// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
// This behavior has the drawback of needing to match routes against
// r.RequestURI instead of r.URL.Path. Any modifications (such as http.StripPrefix)
// to r.URL.Path will not affect routing when this flag is on and thus may
// induce unintended behavior.
//
// If not called, the router will match the unencoded path to the routes.
// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
@@ -172,48 +269,24 @@ func (r *Router) UseEncodedPath() *Router {
return r
}
// ----------------------------------------------------------------------------
// parentRoute
// ----------------------------------------------------------------------------
// getNamedRoutes returns the map where named routes are registered.
func (r *Router) getNamedRoutes() map[string]*Route {
if r.namedRoutes == nil {
if r.parent != nil {
r.namedRoutes = r.parent.getNamedRoutes()
} else {
r.namedRoutes = make(map[string]*Route)
}
}
return r.namedRoutes
}
// getRegexpGroup returns regexp definitions from the parent route, if any.
func (r *Router) getRegexpGroup() *routeRegexpGroup {
if r.parent != nil {
return r.parent.getRegexpGroup()
}
return nil
}
func (r *Router) buildVars(m map[string]string) map[string]string {
if r.parent != nil {
m = r.parent.buildVars(m)
}
return m
}
// ----------------------------------------------------------------------------
// Route factories
// ----------------------------------------------------------------------------
// NewRoute registers an empty route.
func (r *Router) NewRoute() *Route {
route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath}
// initialize a route with a copy of the parent router's configuration
route := &Route{routeConf: copyRouteConf(r.routeConf), namedRoutes: r.namedRoutes}
r.routes = append(r.routes, route)
return route
}
// Name registers a new route with a name.
// See Route.Name().
func (r *Router) Name(name string) *Route {
return r.NewRoute().Name(name)
}
// Handle registers a new route with a matcher for the URL path.
// See Route.Path() and Route.Handler().
func (r *Router) Handle(path string, handler http.Handler) *Route {
@@ -299,10 +372,6 @@ type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
for _, t := range r.routes {
if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" {
continue
}
err := walkFn(t, r, ancestors)
if err == SkipRouter {
continue
@@ -312,10 +381,12 @@ func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
}
for _, sr := range t.matchers {
if h, ok := sr.(*Router); ok {
ancestors = append(ancestors, t)
err := h.walk(walkFn, ancestors)
if err != nil {
return err
}
ancestors = ancestors[:len(ancestors)-1]
}
}
if h, ok := t.handler.(*Router); ok {
@@ -339,6 +410,11 @@ type RouteMatch struct {
Route *Route
Handler http.Handler
Vars map[string]string
// MatchErr is set to appropriate matching error
// It is set to ErrMethodMismatch if there is a mismatch in
// the request method and route method
MatchErr error
}
type contextKey int
@@ -380,28 +456,6 @@ func setCurrentRoute(r *http.Request, val interface{}) *http.Request {
// Helpers
// ----------------------------------------------------------------------------
// getPath returns the escaped path if possible; doing what URL.EscapedPath()
// which was added in go1.5 does
func getPath(req *http.Request) string {
if req.RequestURI != "" {
// Extract the path from RequestURI (which is escaped unlike URL.Path)
// as detailed here as detailed in https://golang.org/pkg/net/url/#URL
// for < 1.5 server side workaround
// http://localhost/path/here?v=1 -> /path/here
path := req.RequestURI
path = strings.TrimPrefix(path, req.URL.Scheme+`://`)
path = strings.TrimPrefix(path, req.URL.Host)
if i := strings.LastIndex(path, "?"); i > -1 {
path = path[:i]
}
if i := strings.LastIndex(path, "#"); i > -1 {
path = path[:i]
}
return path
}
return req.URL.Path
}
// cleanPath returns the canonical path for p, eliminating . and .. elements.
// Borrowed from the net/http package.
func cleanPath(p string) string {
@@ -458,7 +512,7 @@ func mapFromPairsToString(pairs ...string) (map[string]string, error) {
return m, nil
}
// mapFromPairsToRegex converts variadic string paramers to a
// mapFromPairsToRegex converts variadic string parameters to a
// string to regex map.
func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
length, err := checkPairs(pairs...)
@@ -540,3 +594,12 @@ func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]s
}
return true
}
// methodNotAllowed replies to the request with an HTTP status code 405.
func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed)
}
// methodNotAllowedHandler returns a simple request handler
// that replies to each request with a status code 405.
func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) }

File diff suppressed because it is too large Load Diff

View File

@@ -121,12 +121,7 @@ func TestRouteMatchers(t *testing.T) {
var routeMatch RouteMatch
matched := router.Match(request, &routeMatch)
if matched != shouldMatch {
// Need better messages. :)
if matched {
t.Errorf("Should match.")
} else {
t.Errorf("Should not match.")
}
t.Errorf("Expected: %v\nGot: %v\nRequest: %v %v", shouldMatch, matched, request.Method, url)
}
if matched {
@@ -188,7 +183,6 @@ func TestRouteMatchers(t *testing.T) {
match(true)
// 2nd route --------------------------------------------------------------
// Everything match.
reset2()
match(true)
@@ -687,7 +681,7 @@ func TestNewRegexp(t *testing.T) {
}
for pattern, paths := range tests {
p, _ = newRouteRegexp(pattern, false, false, false, false, false)
p, _ = newRouteRegexp(pattern, regexpTypePath, routeRegexpOptions{})
for path, result := range paths {
matches = p.regexp.FindStringSubmatch(path)
if result == nil {

116
regexp.go
View File

@@ -14,6 +14,20 @@ import (
"strings"
)
type routeRegexpOptions struct {
strictSlash bool
useEncodedPath bool
}
type regexpType int
const (
regexpTypePath regexpType = 0
regexpTypeHost regexpType = 1
regexpTypePrefix regexpType = 2
regexpTypeQuery regexpType = 3
)
// newRouteRegexp parses a route template and returns a routeRegexp,
// used to match a host, a path or a query string.
//
@@ -24,7 +38,7 @@ import (
// Previously we accepted only Python-like identifiers for variable
// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
// name and pattern can't be empty, and names can't contain a colon.
func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash, useEncodedPath bool) (*routeRegexp, error) {
func newRouteRegexp(tpl string, typ regexpType, options routeRegexpOptions) (*routeRegexp, error) {
// Check if it is well-formed.
idxs, errBraces := braceIndices(tpl)
if errBraces != nil {
@@ -34,19 +48,18 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
template := tpl
// Now let's parse it.
defaultPattern := "[^/]+"
if matchQuery {
defaultPattern = "[^?&]*"
} else if matchHost {
if typ == regexpTypeQuery {
defaultPattern = ".*"
} else if typ == regexpTypeHost {
defaultPattern = "[^.]+"
matchPrefix = false
}
// Only match strict slash if not matching
if matchPrefix || matchHost || matchQuery {
strictSlash = false
if typ != regexpTypePath {
options.strictSlash = false
}
// Set a flag for strictSlash.
endSlash := false
if strictSlash && strings.HasSuffix(tpl, "/") {
if options.strictSlash && strings.HasSuffix(tpl, "/") {
tpl = tpl[:len(tpl)-1]
endSlash = true
}
@@ -88,18 +101,25 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
// Add the remaining.
raw := tpl[end:]
pattern.WriteString(regexp.QuoteMeta(raw))
if strictSlash {
if options.strictSlash {
pattern.WriteString("[/]?")
}
if matchQuery {
if typ == regexpTypeQuery {
// Add the default pattern if the query value is empty
if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
pattern.WriteString(defaultPattern)
}
}
if !matchPrefix {
if typ != regexpTypePrefix {
pattern.WriteByte('$')
}
var wildcardHostPort bool
if typ == regexpTypeHost {
if !strings.Contains(pattern.String(), ":") {
wildcardHostPort = true
}
}
reverse.WriteString(raw)
if endSlash {
reverse.WriteByte('/')
@@ -118,15 +138,14 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
// Done!
return &routeRegexp{
template: template,
matchHost: matchHost,
matchQuery: matchQuery,
strictSlash: strictSlash,
useEncodedPath: useEncodedPath,
regexp: reg,
reverse: reverse.String(),
varsN: varsN,
varsR: varsR,
template: template,
regexpType: typ,
options: options,
regexp: reg,
reverse: reverse.String(),
varsN: varsN,
varsR: varsR,
wildcardHostPort: wildcardHostPort,
}, nil
}
@@ -135,15 +154,10 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
type routeRegexp struct {
// The unmodified template.
template string
// True for host match, false for path or query string match.
matchHost bool
// True for query string match, false for path and host match.
matchQuery bool
// The strictSlash value defined on the route, but disabled if PathPrefix was used.
strictSlash bool
// Determines whether to use encoded path from getPath function or unencoded
// req.URL.Path for path matching
useEncodedPath bool
// The type of match
regexpType regexpType
// Options for matching
options routeRegexpOptions
// Expanded regexp.
regexp *regexp.Regexp
// Reverse template.
@@ -152,22 +166,31 @@ type routeRegexp struct {
varsN []string
// Variable regexps (validators).
varsR []*regexp.Regexp
// Wildcard host-port (no strict port match in hostname)
wildcardHostPort bool
}
// Match matches the regexp against the URL host or path.
func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
if !r.matchHost {
if r.matchQuery {
if r.regexpType == regexpTypeHost {
host := getHost(req)
if r.wildcardHostPort {
// Don't be strict on the port match
if i := strings.Index(host, ":"); i != -1 {
host = host[:i]
}
}
return r.regexp.MatchString(host)
} else {
if r.regexpType == regexpTypeQuery {
return r.matchQueryString(req)
}
path := req.URL.Path
if r.useEncodedPath {
path = getPath(req)
if r.options.useEncodedPath {
path = req.URL.EscapedPath()
}
return r.regexp.MatchString(path)
}
return r.regexp.MatchString(getHost(req))
}
// url builds a URL part using the given values.
@@ -178,6 +201,9 @@ func (r *routeRegexp) url(values map[string]string) (string, error) {
if !ok {
return "", fmt.Errorf("mux: missing route variable %q", v)
}
if r.regexpType == regexpTypeQuery {
value = url.QueryEscape(value)
}
urlValues[k] = value
}
rv := fmt.Sprintf(r.reverse, urlValues...)
@@ -200,7 +226,7 @@ func (r *routeRegexp) url(values map[string]string) (string, error) {
// For a URL with foo=bar&baz=ding, we return only the relevant key
// value pair for the routeRegexp.
func (r *routeRegexp) getURLQuery(req *http.Request) string {
if !r.matchQuery {
if r.regexpType != regexpTypeQuery {
return ""
}
templateKey := strings.SplitN(r.template, "=", 2)[0]
@@ -258,7 +284,7 @@ type routeRegexpGroup struct {
}
// setMatch extracts the variables from the URL once a route matches.
func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
func (v routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
// Store host variables.
if v.host != nil {
host := getHost(req)
@@ -269,7 +295,7 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
}
path := req.URL.Path
if r.useEncodedPath {
path = getPath(req)
path = req.URL.EscapedPath()
}
// Store path variables.
if v.path != nil {
@@ -277,7 +303,7 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
if len(matches) > 0 {
extractVars(path, matches, v.path.varsN, m.Vars)
// Check if we should redirect.
if v.path.strictSlash {
if v.path.options.strictSlash {
p1 := strings.HasSuffix(path, "/")
p2 := strings.HasSuffix(v.path.template, "/")
if p1 != p2 {
@@ -287,7 +313,7 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
} else {
u.Path += "/"
}
m.Handler = http.RedirectHandler(u.String(), 301)
m.Handler = http.RedirectHandler(u.String(), http.StatusMovedPermanently)
}
}
}
@@ -303,17 +329,13 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
}
// getHost tries its best to return the request host.
// According to section 14.23 of RFC 2616 the Host header
// can include the port number if the default value of 80 is not used.
func getHost(r *http.Request) string {
if r.URL.IsAbs() {
return r.URL.Host
}
host := r.Host
// Slice off any port information.
if i := strings.Index(host, ":"); i != -1 {
host = host[:i]
}
return host
return r.Host
}
func extractVars(input string, matches []int, names []string, output map[string]string) {

262
route.go
View File

@@ -15,22 +15,8 @@ import (
// Route stores information to match a request and build URLs.
type Route struct {
// Parent where the route was registered (a Router).
parent parentRoute
// Request handler for the route.
handler http.Handler
// List of matchers.
matchers []matcher
// Manager for the variables from host and path.
regexp *routeRegexpGroup
// If true, when the path pattern is "/path/", accessing "/path" will
// redirect to the former and vice versa.
strictSlash bool
// If true, when the path pattern is "/path//to", accessing "/path//to"
// will not redirect
skipClean bool
// If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
useEncodedPath bool
// If true, this route never matches: it is only used to build URLs.
buildOnly bool
// The name used to build URLs.
@@ -38,9 +24,15 @@ type Route struct {
// Error resulted from building a route.
err error
buildVarsFunc BuildVarsFunc
// "global" reference to all named routes
namedRoutes map[string]*Route
// config possibly passed in from `Router`
routeConf
}
// SkipClean reports whether path cleaning is enabled for this route via
// Router.SkipClean.
func (r *Route) SkipClean() bool {
return r.skipClean
}
@@ -50,12 +42,45 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
if r.buildOnly || r.err != nil {
return false
}
var matchErr error
// Match everything.
for _, m := range r.matchers {
if matched := m.Match(req, match); !matched {
if _, ok := m.(methodMatcher); ok {
matchErr = ErrMethodMismatch
continue
}
// Ignore ErrNotFound errors. These errors arise from match call
// to Subrouters.
//
// This prevents subsequent matching subrouters from failing to
// run middleware. If not ignored, the middleware would see a
// non-nil MatchErr and be skipped, even when there was a
// matching route.
if match.MatchErr == ErrNotFound {
match.MatchErr = nil
}
matchErr = nil
return false
}
}
if matchErr != nil {
match.MatchErr = matchErr
return false
}
if match.MatchErr == ErrMethodMismatch {
// We found a route which matches request method, clear MatchErr
match.MatchErr = nil
// Then override the mis-matched handler
match.Handler = r.handler
}
// Yay, we have a match. Let's collect some info about it.
if match.Route == nil {
match.Route = r
@@ -66,10 +91,9 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
if match.Vars == nil {
match.Vars = make(map[string]string)
}
// Set variables.
if r.regexp != nil {
r.regexp.setMatch(req, match, r)
}
r.regexp.setMatch(req, match, r)
return true
}
@@ -111,7 +135,7 @@ func (r *Route) GetHandler() http.Handler {
// Name -----------------------------------------------------------------------
// Name sets the name for the route, used to build URLs.
// If the name was registered already it will be overwritten.
// It is an error to call Name more than once on a route.
func (r *Route) Name(name string) *Route {
if r.name != "" {
r.err = fmt.Errorf("mux: route already has name %q, can't set %q",
@@ -119,7 +143,7 @@ func (r *Route) Name(name string) *Route {
}
if r.err == nil {
r.name = name
r.getNamedRoutes()[name] = r
r.namedRoutes[name] = r
}
return r
}
@@ -147,20 +171,22 @@ func (r *Route) addMatcher(m matcher) *Route {
}
// addRegexpMatcher adds a host or path matcher and builder to a route.
func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error {
func (r *Route) addRegexpMatcher(tpl string, typ regexpType) error {
if r.err != nil {
return r.err
}
r.regexp = r.getRegexpGroup()
if !matchHost && !matchQuery {
if tpl == "/" && (len(tpl) == 0 || tpl[0] != '/') {
if typ == regexpTypePath || typ == regexpTypePrefix {
if len(tpl) > 0 && tpl[0] != '/' {
return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
}
if r.regexp.path != nil {
tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl
}
}
rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash, r.useEncodedPath)
rr, err := newRouteRegexp(tpl, typ, routeRegexpOptions{
strictSlash: r.strictSlash,
useEncodedPath: r.useEncodedPath,
})
if err != nil {
return err
}
@@ -169,7 +195,7 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
return err
}
}
if matchHost {
if typ == regexpTypeHost {
if r.regexp.path != nil {
if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil {
return err
@@ -182,7 +208,7 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
return err
}
}
if matchQuery {
if typ == regexpTypeQuery {
r.regexp.queries = append(r.regexp.queries, rr)
} else {
r.regexp.path = rr
@@ -234,7 +260,8 @@ func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
// "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both the request header matches both regular expressions.
// It the value is an empty string, it will match any value if the key is set.
// If the value is an empty string, it will match any value if the key is set.
// Use the start and end of string anchors (^ and $) to match an exact value.
func (r *Route) HeadersRegexp(pairs ...string) *Route {
if r.err == nil {
var headers map[string]*regexp.Regexp
@@ -264,7 +291,7 @@ func (r *Route) HeadersRegexp(pairs ...string) *Route {
// Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request).
func (r *Route) Host(tpl string) *Route {
r.err = r.addRegexpMatcher(tpl, true, false, false)
r.err = r.addRegexpMatcher(tpl, regexpTypeHost)
return r
}
@@ -324,7 +351,7 @@ func (r *Route) Methods(methods ...string) *Route {
// Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request).
func (r *Route) Path(tpl string) *Route {
r.err = r.addRegexpMatcher(tpl, false, false, false)
r.err = r.addRegexpMatcher(tpl, regexpTypePath)
return r
}
@@ -340,7 +367,7 @@ func (r *Route) Path(tpl string) *Route {
// Also note that the setting of Router.StrictSlash() has no effect on routes
// with a PathPrefix matcher.
func (r *Route) PathPrefix(tpl string) *Route {
r.err = r.addRegexpMatcher(tpl, false, true, false)
r.err = r.addRegexpMatcher(tpl, regexpTypePrefix)
return r
}
@@ -356,7 +383,7 @@ func (r *Route) PathPrefix(tpl string) *Route {
// The above route will only match if the URL contains the defined queries
// values, e.g.: ?foo=bar&id=42.
//
// It the value is an empty string, it will match any value if the key is set.
// If the value is an empty string, it will match any value if the key is set.
//
// Variables can define an optional regexp pattern to be matched:
//
@@ -371,7 +398,7 @@ func (r *Route) Queries(pairs ...string) *Route {
return nil
}
for i := 0; i < length; i += 2 {
if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil {
if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], regexpTypeQuery); r.err != nil {
return r
}
}
@@ -394,6 +421,9 @@ func (r *Route) Schemes(schemes ...string) *Route {
for k, v := range schemes {
schemes[k] = strings.ToLower(v)
}
if len(schemes) > 0 {
r.buildScheme = schemes[0]
}
return r.addMatcher(schemeMatcher(schemes))
}
@@ -406,7 +436,15 @@ type BuildVarsFunc func(map[string]string) map[string]string
// BuildVarsFunc adds a custom function to be used to modify build variables
// before a route's URL is built.
func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
r.buildVarsFunc = f
if r.buildVarsFunc != nil {
// compose the old and new functions
old := r.buildVarsFunc
r.buildVarsFunc = func(m map[string]string) map[string]string {
return f(old(m))
}
} else {
r.buildVarsFunc = f
}
return r
}
@@ -425,7 +463,8 @@ func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
// Here, the routes registered in the subrouter won't be tested if the host
// doesn't match.
func (r *Route) Subrouter() *Router {
router := &Router{parent: r, strictSlash: r.strictSlash}
// initialize a subrouter with a copy of the parent route's configuration
router := &Router{routeConf: copyRouteConf(r.routeConf), namedRoutes: r.namedRoutes}
r.addMatcher(router)
return router
}
@@ -469,30 +508,38 @@ func (r *Route) URL(pairs ...string) (*url.URL, error) {
if r.err != nil {
return nil, r.err
}
if r.regexp == nil {
return nil, errors.New("mux: route doesn't have a host or path")
}
values, err := r.prepareVars(pairs...)
if err != nil {
return nil, err
}
var scheme, host, path string
queries := make([]string, 0, len(r.regexp.queries))
if r.regexp.host != nil {
// Set a default scheme.
scheme = "http"
if host, err = r.regexp.host.url(values); err != nil {
return nil, err
}
scheme = "http"
if r.buildScheme != "" {
scheme = r.buildScheme
}
}
if r.regexp.path != nil {
if path, err = r.regexp.path.url(values); err != nil {
return nil, err
}
}
for _, q := range r.regexp.queries {
var query string
if query, err = q.url(values); err != nil {
return nil, err
}
queries = append(queries, query)
}
return &url.URL{
Scheme: scheme,
Host: host,
Path: path,
Scheme: scheme,
Host: host,
Path: path,
RawQuery: strings.Join(queries, "&"),
}, nil
}
@@ -503,7 +550,7 @@ func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
if r.err != nil {
return nil, r.err
}
if r.regexp == nil || r.regexp.host == nil {
if r.regexp.host == nil {
return nil, errors.New("mux: route doesn't have a host")
}
values, err := r.prepareVars(pairs...)
@@ -514,10 +561,14 @@ func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
if err != nil {
return nil, err
}
return &url.URL{
u := &url.URL{
Scheme: "http",
Host: host,
}, nil
}
if r.buildScheme != "" {
u.Scheme = r.buildScheme
}
return u, nil
}
// URLPath builds the path part of the URL for a route. See Route.URL().
@@ -527,7 +578,7 @@ func (r *Route) URLPath(pairs ...string) (*url.URL, error) {
if r.err != nil {
return nil, r.err
}
if r.regexp == nil || r.regexp.path == nil {
if r.regexp.path == nil {
return nil, errors.New("mux: route doesn't have a path")
}
values, err := r.prepareVars(pairs...)
@@ -552,12 +603,80 @@ func (r *Route) GetPathTemplate() (string, error) {
if r.err != nil {
return "", r.err
}
if r.regexp == nil || r.regexp.path == nil {
if r.regexp.path == nil {
return "", errors.New("mux: route doesn't have a path")
}
return r.regexp.path.template, nil
}
// GetPathRegexp returns the expanded regular expression used to match route path.
// This is useful for building simple REST API documentation and for instrumentation
// against third-party services.
// An error will be returned if the route does not define a path.
func (r *Route) GetPathRegexp() (string, error) {
if r.err != nil {
return "", r.err
}
if r.regexp.path == nil {
return "", errors.New("mux: route does not have a path")
}
return r.regexp.path.regexp.String(), nil
}
// GetQueriesRegexp returns the expanded regular expressions used to match the
// route queries.
// This is useful for building simple REST API documentation and for instrumentation
// against third-party services.
// An error will be returned if the route does not have queries.
func (r *Route) GetQueriesRegexp() ([]string, error) {
if r.err != nil {
return nil, r.err
}
if r.regexp.queries == nil {
return nil, errors.New("mux: route doesn't have queries")
}
var queries []string
for _, query := range r.regexp.queries {
queries = append(queries, query.regexp.String())
}
return queries, nil
}
// GetQueriesTemplates returns the templates used to build the
// query matching.
// This is useful for building simple REST API documentation and for instrumentation
// against third-party services.
// An error will be returned if the route does not define queries.
func (r *Route) GetQueriesTemplates() ([]string, error) {
if r.err != nil {
return nil, r.err
}
if r.regexp.queries == nil {
return nil, errors.New("mux: route doesn't have queries")
}
var queries []string
for _, query := range r.regexp.queries {
queries = append(queries, query.template)
}
return queries, nil
}
// GetMethods returns the methods the route matches against
// This is useful for building simple REST API documentation and for instrumentation
// against third-party services.
// An error will be returned if route does not have methods.
func (r *Route) GetMethods() ([]string, error) {
if r.err != nil {
return nil, r.err
}
for _, m := range r.matchers {
if methods, ok := m.(methodMatcher); ok {
return []string(methods), nil
}
}
return nil, errors.New("mux: route doesn't have methods")
}
// GetHostTemplate returns the template used to build the
// route match.
// This is useful for building simple REST API documentation and for instrumentation
@@ -567,7 +686,7 @@ func (r *Route) GetHostTemplate() (string, error) {
if r.err != nil {
return "", r.err
}
if r.regexp == nil || r.regexp.host == nil {
if r.regexp.host == nil {
return "", errors.New("mux: route doesn't have a host")
}
return r.regexp.host.template, nil
@@ -584,53 +703,8 @@ func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
}
func (r *Route) buildVars(m map[string]string) map[string]string {
if r.parent != nil {
m = r.parent.buildVars(m)
}
if r.buildVarsFunc != nil {
m = r.buildVarsFunc(m)
}
return m
}
// ----------------------------------------------------------------------------
// parentRoute
// ----------------------------------------------------------------------------
// parentRoute allows routes to know about parent host and path definitions.
type parentRoute interface {
getNamedRoutes() map[string]*Route
getRegexpGroup() *routeRegexpGroup
buildVars(map[string]string) map[string]string
}
// getNamedRoutes returns the map where named routes are registered.
func (r *Route) getNamedRoutes() map[string]*Route {
if r.parent == nil {
// During tests router is not always set.
r.parent = NewRouter()
}
return r.parent.getNamedRoutes()
}
// getRegexpGroup returns regexp definitions from this route.
func (r *Route) getRegexpGroup() *routeRegexpGroup {
if r.regexp == nil {
if r.parent == nil {
// During tests router is not always set.
r.parent = NewRouter()
}
regexp := r.parent.getRegexpGroup()
if regexp == nil {
r.regexp = new(routeRegexpGroup)
} else {
// Copy.
r.regexp = &routeRegexpGroup{
host: regexp.host,
path: regexp.path,
queries: regexp.queries,
}
}
}
return r.regexp
}

19
test_helpers.go Normal file
View File

@@ -0,0 +1,19 @@
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mux
import "net/http"
// SetURLVars sets the URL variables for the given request, to be accessed via
// mux.Vars for testing route behaviour. Arguments are not modified, a shallow
// copy is returned.
//
// This API should only be used for testing purposes; it provides a way to
// inject variables into the request context. Alternatively, URL variables
// can be set by making a route that captures the required variables,
// starting a server and sending the request to that server.
func SetURLVars(r *http.Request, val map[string]string) *http.Request {
return setVars(r, val)
}