Bump gorilla mux to 1.6.2

**What**
- Update the gopkg.toml

Signed-off-by: Lucas Roesler <roesler.lucas@gmail.com>
This commit is contained in:
Lucas Roesler 2018-11-03 16:03:40 +01:00 committed by Alex Ellis
parent 09736be293
commit c9befd78e7
16 changed files with 1462 additions and 195 deletions

60
gateway/Gopkg.lock generated
View File

@ -3,124 +3,160 @@
[[projects]]
branch = "master"
digest = "1:0c5485088ce274fac2e931c1b979f2619345097b39d91af3239977114adf0320"
name = "github.com/beorn7/perks"
packages = ["quantile"]
pruneopts = ""
revision = "4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9"
[[projects]]
digest = "1:a9e4ff75555e4500e409dc87c1d708b090bb8dd77f889bbf266773f3dc23af70"
name = "github.com/docker/distribution"
packages = ["uuid"]
pruneopts = ""
revision = "48294d928ced5dd9b378f7fd7c6f5da3ff3f2c89"
version = "v2.6.2"
[[projects]]
digest = "1:70a80170917a15e1ff02faab5f9e716e945e0676e86599ba144d38f96e30c3bf"
name = "github.com/gogo/protobuf"
packages = [
"gogoproto",
"proto",
"protoc-gen-gogo/descriptor"
"protoc-gen-gogo/descriptor",
]
pruneopts = ""
revision = "342cbe0a04158f6dcb03ca0079991a51a4248c02"
version = "v0.5"
[[projects]]
branch = "master"
digest = "1:3b760d3b93f994df8eb1d9ebfad17d3e9e37edcb7f7efaa15b427c0d7a64f4e4"
name = "github.com/golang/protobuf"
packages = ["proto"]
pruneopts = ""
revision = "1e59b77b52bf8e4b449a57e6f79f21226d571845"
[[projects]]
digest = "1:20ed7daa9b3b38b6d1d39b48ab3fd31122be5419461470d0c28de3e121c93ecf"
name = "github.com/gorilla/context"
packages = ["."]
pruneopts = ""
revision = "1ea25387ff6f684839d82767c1733ff4d4d15d0a"
version = "v1.1"
[[projects]]
digest = "1:c2c8666b4836c81a1d247bdf21c6a6fc1ab586538ab56f74437c2e0df5c375e1"
name = "github.com/gorilla/mux"
packages = ["."]
revision = "7f08801859139f86dfafd1c296e2cba9a80d292e"
version = "v1.6.0"
pruneopts = ""
revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf"
version = "v1.6.2"
[[projects]]
digest = "1:4c23ced97a470b17d9ffd788310502a077b9c1f60221a85563e49696276b4147"
name = "github.com/matttproud/golang_protobuf_extensions"
packages = ["pbutil"]
pruneopts = ""
revision = "3247c84500bff8d9fb6d579d800f20b3e091582c"
version = "v1.0.0"
[[projects]]
digest = "1:665af347df4c5d1ae4c3eacd0754f5337a301f6a3f2444c9993b996605c8c02b"
name = "github.com/nats-io/go-nats"
packages = [
".",
"encoders/builtin",
"util"
"util",
]
pruneopts = ""
revision = "062418ea1c2181f52dc0f954f6204370519a868b"
version = "v1.5.0"
[[projects]]
digest = "1:ca0ffe35a7afa99d614845251f508505188d4117b87d368ee2f4b84c85f3fd29"
name = "github.com/nats-io/go-nats-streaming"
packages = [
".",
"pb"
"pb",
]
pruneopts = ""
revision = "e15a53f85e4932540600a16b56f6c4f65f58176f"
version = "v0.4.0"
[[projects]]
digest = "1:be61e8224b84064109eaba8157cbb4bbe6ca12443e182b6624fdfa1c0dcf53d9"
name = "github.com/nats-io/nuid"
packages = ["."]
pruneopts = ""
revision = "289cccf02c178dc782430d534e3c1f5b72af807f"
version = "v1.0.0"
[[projects]]
digest = "1:3eb611e5a4c84bb93879f9704b2fdc0ea9b29e59f465b3b8b2af382a747ef86f"
name = "github.com/openfaas/faas-provider"
packages = [
".",
"types"
]
packages = ["auth"]
pruneopts = ""
revision = "9ce928bc82cbb2642e6d534f93a7904116179e6c"
version = "0.7.0"
[[projects]]
digest = "1:26136842b63206aa4f8d20730edcdf88bd0e89f81df51b199b8baf9b9ed288bc"
name = "github.com/openfaas/nats-queue-worker"
packages = ["handler"]
pruneopts = ""
revision = "15287c9b2af293cee0c545ccc014a68e1f0a4424"
version = "0.4.7"
[[projects]]
digest = "1:4142d94383572e74b42352273652c62afec5b23f325222ed09198f46009022d1"
name = "github.com/prometheus/client_golang"
packages = ["prometheus"]
pruneopts = ""
revision = "c5b7fccd204277076155f10851dad72b76a49317"
version = "v0.8.0"
[[projects]]
branch = "master"
digest = "1:60aca47f4eeeb972f1b9da7e7db51dee15ff6c59f7b401c1588b8e6771ba15ef"
name = "github.com/prometheus/client_model"
packages = ["go"]
pruneopts = ""
revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c"
[[projects]]
branch = "master"
digest = "1:e3aa5178be4fc4ae8cdb37d11c02f7490c00450a9f419e6aa84d02d3b47e90d2"
name = "github.com/prometheus/common"
packages = [
"expfmt",
"internal/bitbucket.org/ww/goautoneg",
"model"
"model",
]
pruneopts = ""
revision = "2e54d0b93cba2fd133edc32211dcc32c06ef72ca"
[[projects]]
branch = "master"
digest = "1:f0857d075687b4ddebb10c8403d5fec9f093f7208b34ed5b6f3101ee2e77cec5"
name = "github.com/prometheus/procfs"
packages = [
".",
"xfs"
"xfs",
]
pruneopts = ""
revision = "b15cd069a83443be3154b719d0cc9fe8117f09fb"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "28590014be90eceddef008d7ef4843165d708e8358c428ad907c50e363af424f"
input-imports = [
"github.com/docker/distribution/uuid",
"github.com/gorilla/mux",
"github.com/openfaas/faas-provider/auth",
"github.com/openfaas/nats-queue-worker/handler",
"github.com/prometheus/client_golang/prometheus",
"github.com/prometheus/client_model/go",
]
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -2,7 +2,7 @@ ignored = ["github.com/openfaas/faas/gateway/queue"]
[[constraint]]
name = "github.com/gorilla/mux"
version = "1.6.0"
version = "1.6.2"
[[constraint]]
name = "github.com/nats-io/go-nats-streaming"

View File

@ -3,11 +3,12 @@ sudo: false
matrix:
include:
- go: 1.5
- go: 1.6
- go: 1.7
- go: 1.8
- go: 1.9
- go: 1.5.x
- go: 1.6.x
- go: 1.7.x
- go: 1.8.x
- go: 1.9.x
- go: 1.10.x
- go: tip
allow_failures:
- go: tip

View File

@ -0,0 +1,11 @@
**What version of Go are you running?** (Paste the output of `go version`)
**What version of gorilla/mux are you at?** (Paste the output of `git rev-parse HEAD` inside `$GOPATH/src/github.com/gorilla/mux`)
**Describe your problem** (and what you have tried so far)
**Paste a minimal, runnable, reproduction of your issue below** (use backticks to format it)

View File

@ -1,5 +1,5 @@
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)
[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
@ -27,6 +27,9 @@ The name mux stands for "HTTP request multiplexer". Like the standard `http.Serv
* [Static Files](#static-files)
* [Registered URLs](#registered-urls)
* [Walking Routes](#walking-routes)
* [Graceful Shutdown](#graceful-shutdown)
* [Middleware](#middleware)
* [Testing Handlers](#testing-handlers)
* [Full Example](#full-example)
---
@ -45,11 +48,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)
}
```
@ -68,9 +71,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"])
}
```
@ -122,7 +125,7 @@ r.Queries("key", "value")
```go
r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
return r.ProtoMajor == 0
return r.ProtoMajor == 0
})
```
@ -176,91 +179,34 @@ s.HandleFunc("/{key}/", ProductHandler)
// "/products/{key}/details"
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"
"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}")
r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
t, err := route.GetPathTemplate()
if err != nil {
return err
}
qt, err := route.GetQueriesTemplates()
if err != nil {
return err
}
// p will contain regular expression is compatible with regular expression in Perl, Python, and other languages.
// for instance the regular expression for path '/articles/{id}' will be '^/articles/(?P<v0>[^/]+)$'
p, err := route.GetPathRegexp()
if err != nil {
return err
}
// qr will contain a list of regular expressions with the same semantics as GetPathRegexp,
// just applied to the Queries pairs instead, e.g., 'Queries("surname", "{surname}") will return
// {"^surname=(?P<v0>.*)$}. Where each combined query pair will have an entry in the list.
qr, err := route.GetQueriesRegexp()
if err != nil {
return err
}
m, err := route.GetMethods()
if err != nil {
return err
}
fmt.Println(strings.Join(m, ","), strings.Join(qt, ","), strings.Join(qr, ","), t, p)
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,
}
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())
log.Fatal(srv.ListenAndServe())
}
```
@ -345,42 +291,330 @@ url, err := r.Get("article").URL("subdomain", "news",
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.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}")
r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
t, err := route.GetPathTemplate()
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.
### 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.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
// 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 {
return err
t.Fatal(err)
}
qt, err := route.GetQueriesTemplates()
if err != nil {
return 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)
}
// p will contain a regular expression that is compatible with regular expressions in Perl, Python, and other languages.
// For example, the regular expression for path '/articles/{id}' will be '^/articles/(?P<v0>[^/]+)$'.
p, err := route.GetPathRegexp()
if err != nil {
return err
// 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)
}
// qr will contain a list of regular expressions with the same semantics as GetPathRegexp,
// just applied to the Queries pairs instead, e.g., 'Queries("surname", "{surname}") will return
// {"^surname=(?P<v0>.*)$}. Where each combined query pair will have an entry in the list.
qr, err := route.GetQueriesRegexp()
if err != nil {
return err
}
```
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},
}
m, err := route.GetMethods()
if err != nil {
return err
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)
}
}
fmt.Println(strings.Join(m, ","), strings.Join(qt, ","), strings.Join(qr, ","), t, p)
return nil
})
}
```
## Full Example
@ -391,22 +625,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

@ -238,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{}
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{}
amw.Populate()
r.Use(amw.Middleware)
}

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"]
}

72
gateway/vendor/github.com/gorilla/mux/middleware.go generated vendored Normal file
View File

@ -0,0 +1,72 @@
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 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.
func CORSMethodMiddleware(r *Router) MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
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
})
if err == nil {
w.Header().Set("Access-Control-Allow-Methods", strings.Join(append(allMethods, "OPTIONS"), ","))
if req.Method == "OPTIONS" {
return
}
}
next.ServeHTTP(w, req)
})
}
}

View File

@ -0,0 +1,377 @@
package mux
import (
"bytes"
"net/http"
"net/http/httptest"
"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 was not added correctly")
}
router.Use(mw.Middleware)
if len(router.middlewares) != 2 {
t.Fatal("MiddlewareFunc method was not added correctly")
}
banalMw := func(handler http.Handler) http.Handler {
return handler
}
router.Use(banalMw)
if len(router.middlewares) != 3 {
t.Fatal("MiddlewareFunc method 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", "/")
// Test regular middleware call
router.ServeHTTP(rw, req)
if mw.timesCalled != 1 {
t.Fatalf("Expected %d calls, but got only %d", 1, mw.timesCalled)
}
// Middleware should not be called for 404
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)
}
// Middleware should not be called if there is a method mismatch
req = newRequest("POST", "/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 1 {
t.Fatalf("Expected %d calls, but got only %d", 1, mw.timesCalled)
}
// Add the middleware again as function
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", "/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 0 {
t.Fatalf("Expected %d calls, but got only %d", 0, mw.timesCalled)
}
req = newRequest("GET", "/sub/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 0 {
t.Fatalf("Expected %d calls, but got only %d", 0, mw.timesCalled)
}
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)
}
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)
}
router.useInterface(mw)
req = newRequest("GET", "/")
router.ServeHTTP(rw, req)
if mw.timesCalled != 2 {
t.Fatalf("Expected %d calls, but got only %d", 2, mw.timesCalled)
}
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)
})
rw := NewRecorder()
req := newRequest("GET", "/")
// Test handler-only call
router.ServeHTTP(rw, req)
if bytes.Compare(rw.Body.Bytes(), handlerStr) != 0 {
t.Fatal("Handler response is not what it should be")
}
// Test middleware call
rw = NewRecorder()
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.Compare(rw.Body.Bytes(), append(mwStr, handlerStr...)) != 0 {
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
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")
}
// Test not found call with custom handler
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)
})
})
// Test method mismatch
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")
}
// Test not found call
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)
})
})
// Test not found call for default handler
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")
}
// Test not found call with custom handler
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)
})
})
// Test method mismatch without custom handler
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")
}
// Test method mismatch with custom handler
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) {
router := NewRouter()
cases := []struct {
path string
response string
method string
testURL string
expectedAllowedMethods string
}{
{"/g/{o}", "a", "POST", "/g/asdf", "POST,PUT,GET,OPTIONS"},
{"/g/{o}", "b", "PUT", "/g/bla", "POST,PUT,GET,OPTIONS"},
{"/g/{o}", "c", "GET", "/g/orilla", "POST,PUT,GET,OPTIONS"},
{"/g", "d", "POST", "/g", "POST,OPTIONS"},
}
for _, tt := range cases {
router.HandleFunc(tt.path, stringHandler(tt.response)).Methods(tt.method)
}
router.Use(CORSMethodMiddleware(router))
for _, tt := range cases {
rr := httptest.NewRecorder()
req := newRequest(tt.method, tt.testURL)
router.ServeHTTP(rr, req)
if rr.Body.String() != tt.response {
t.Errorf("Expected body '%s', found '%s'", tt.response, rr.Body.String())
}
allowedMethods := rr.HeaderMap.Get("Access-Control-Allow-Methods")
if allowedMethods != tt.expectedAllowedMethods {
t.Errorf("Expected Access-Control-Allow-Methods '%s', found '%s'", tt.expectedAllowedMethods, allowedMethods)
}
}
}

View File

@ -13,8 +13,11 @@ import (
)
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 = errors.New("no matching route was found")
// ErrNotFound is returned when no route match is found.
ErrNotFound = errors.New("no matching route was found")
)
// NewRouter returns a new router instance.
@ -63,6 +66,8 @@ type Router struct {
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
}
// Match attempts to match the given request against the router's registered routes.
@ -79,6 +84,12 @@ type Router struct {
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
}
}
@ -87,9 +98,9 @@ func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
if r.MethodNotAllowedHandler != nil {
match.Handler = r.MethodNotAllowedHandler
return true
} else {
return false
}
return false
}
// Closest match for a router (includes sub-routers)
@ -147,6 +158,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if !r.KeepContext {
defer contextClear(req)
}
handler.ServeHTTP(w, req)
}
@ -164,13 +176,18 @@ func (r *Router) GetRoute(name string) *Route {
// 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
@ -196,10 +213,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"

View File

@ -25,7 +25,7 @@ func (r *Route) GoString() string {
}
func (r *routeRegexp) GoString() string {
return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR)
return fmt.Sprintf("&routeRegexp{template: %q, regexpType: %v, options: %v, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.regexpType, r.options, r.regexp.String(), r.reverse, r.varsN, r.varsR)
}
type routeTest struct {
@ -1967,6 +1967,327 @@ func TestErrMatchNotFound(t *testing.T) {
}
}
// methodsSubrouterTest models the data necessary for testing handler
// matching for subrouters created after HTTP methods matcher registration.
type methodsSubrouterTest struct {
title string
wantCode int
router *Router
// method is the input into the request and expected response
method string
// input request path
path string
// redirectTo is the expected location path for strict-slash matches
redirectTo string
}
// methodHandler writes the method string in response.
func methodHandler(method string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(method))
}
}
// TestMethodsSubrouterCatchall matches handlers for subrouters where a
// catchall handler is set for a mis-matching method.
func TestMethodsSubrouterCatchall(t *testing.T) {
t.Parallel()
router := NewRouter()
router.Methods("PATCH").Subrouter().PathPrefix("/").HandlerFunc(methodHandler("PUT"))
router.Methods("GET").Subrouter().HandleFunc("/foo", methodHandler("GET"))
router.Methods("POST").Subrouter().HandleFunc("/foo", methodHandler("POST"))
router.Methods("DELETE").Subrouter().HandleFunc("/foo", methodHandler("DELETE"))
tests := []methodsSubrouterTest{
{
title: "match GET handler",
router: router,
path: "http://localhost/foo",
method: "GET",
wantCode: http.StatusOK,
},
{
title: "match POST handler",
router: router,
method: "POST",
path: "http://localhost/foo",
wantCode: http.StatusOK,
},
{
title: "match DELETE handler",
router: router,
method: "DELETE",
path: "http://localhost/foo",
wantCode: http.StatusOK,
},
{
title: "disallow PUT method",
router: router,
method: "PUT",
path: "http://localhost/foo",
wantCode: http.StatusMethodNotAllowed,
},
}
for _, test := range tests {
testMethodsSubrouter(t, test)
}
}
// TestMethodsSubrouterStrictSlash matches handlers on subrouters with
// strict-slash matchers.
func TestMethodsSubrouterStrictSlash(t *testing.T) {
t.Parallel()
router := NewRouter()
sub := router.PathPrefix("/").Subrouter()
sub.StrictSlash(true).Path("/foo").Methods("GET").Subrouter().HandleFunc("", methodHandler("GET"))
sub.StrictSlash(true).Path("/foo/").Methods("PUT").Subrouter().HandleFunc("/", methodHandler("PUT"))
sub.StrictSlash(true).Path("/foo/").Methods("POST").Subrouter().HandleFunc("/", methodHandler("POST"))
tests := []methodsSubrouterTest{
{
title: "match POST handler",
router: router,
method: "POST",
path: "http://localhost/foo/",
wantCode: http.StatusOK,
},
{
title: "match GET handler",
router: router,
method: "GET",
path: "http://localhost/foo",
wantCode: http.StatusOK,
},
{
title: "match POST handler, redirect strict-slash",
router: router,
method: "POST",
path: "http://localhost/foo",
redirectTo: "http://localhost/foo/",
wantCode: http.StatusMovedPermanently,
},
{
title: "match GET handler, redirect strict-slash",
router: router,
method: "GET",
path: "http://localhost/foo/",
redirectTo: "http://localhost/foo",
wantCode: http.StatusMovedPermanently,
},
{
title: "disallow DELETE method",
router: router,
method: "DELETE",
path: "http://localhost/foo",
wantCode: http.StatusMethodNotAllowed,
},
}
for _, test := range tests {
testMethodsSubrouter(t, test)
}
}
// TestMethodsSubrouterPathPrefix matches handlers on subrouters created
// on a router with a path prefix matcher and method matcher.
func TestMethodsSubrouterPathPrefix(t *testing.T) {
t.Parallel()
router := NewRouter()
router.PathPrefix("/1").Methods("POST").Subrouter().HandleFunc("/2", methodHandler("POST"))
router.PathPrefix("/1").Methods("DELETE").Subrouter().HandleFunc("/2", methodHandler("DELETE"))
router.PathPrefix("/1").Methods("PUT").Subrouter().HandleFunc("/2", methodHandler("PUT"))
router.PathPrefix("/1").Methods("POST").Subrouter().HandleFunc("/2", methodHandler("POST2"))
tests := []methodsSubrouterTest{
{
title: "match first POST handler",
router: router,
method: "POST",
path: "http://localhost/1/2",
wantCode: http.StatusOK,
},
{
title: "match DELETE handler",
router: router,
method: "DELETE",
path: "http://localhost/1/2",
wantCode: http.StatusOK,
},
{
title: "match PUT handler",
router: router,
method: "PUT",
path: "http://localhost/1/2",
wantCode: http.StatusOK,
},
{
title: "disallow PATCH method",
router: router,
method: "PATCH",
path: "http://localhost/1/2",
wantCode: http.StatusMethodNotAllowed,
},
}
for _, test := range tests {
testMethodsSubrouter(t, test)
}
}
// TestMethodsSubrouterSubrouter matches handlers on subrouters produced
// from method matchers registered on a root subrouter.
func TestMethodsSubrouterSubrouter(t *testing.T) {
t.Parallel()
router := NewRouter()
sub := router.PathPrefix("/1").Subrouter()
sub.Methods("POST").Subrouter().HandleFunc("/2", methodHandler("POST"))
sub.Methods("GET").Subrouter().HandleFunc("/2", methodHandler("GET"))
sub.Methods("PATCH").Subrouter().HandleFunc("/2", methodHandler("PATCH"))
sub.HandleFunc("/2", methodHandler("PUT")).Subrouter().Methods("PUT")
sub.HandleFunc("/2", methodHandler("POST2")).Subrouter().Methods("POST")
tests := []methodsSubrouterTest{
{
title: "match first POST handler",
router: router,
method: "POST",
path: "http://localhost/1/2",
wantCode: http.StatusOK,
},
{
title: "match GET handler",
router: router,
method: "GET",
path: "http://localhost/1/2",
wantCode: http.StatusOK,
},
{
title: "match PATCH handler",
router: router,
method: "PATCH",
path: "http://localhost/1/2",
wantCode: http.StatusOK,
},
{
title: "match PUT handler",
router: router,
method: "PUT",
path: "http://localhost/1/2",
wantCode: http.StatusOK,
},
{
title: "disallow DELETE method",
router: router,
method: "DELETE",
path: "http://localhost/1/2",
wantCode: http.StatusMethodNotAllowed,
},
}
for _, test := range tests {
testMethodsSubrouter(t, test)
}
}
// TestMethodsSubrouterPathVariable matches handlers on matching paths
// with path variables in them.
func TestMethodsSubrouterPathVariable(t *testing.T) {
t.Parallel()
router := NewRouter()
router.Methods("GET").Subrouter().HandleFunc("/foo", methodHandler("GET"))
router.Methods("POST").Subrouter().HandleFunc("/{any}", methodHandler("POST"))
router.Methods("DELETE").Subrouter().HandleFunc("/1/{any}", methodHandler("DELETE"))
router.Methods("PUT").Subrouter().HandleFunc("/1/{any}", methodHandler("PUT"))
tests := []methodsSubrouterTest{
{
title: "match GET handler",
router: router,
method: "GET",
path: "http://localhost/foo",
wantCode: http.StatusOK,
},
{
title: "match POST handler",
router: router,
method: "POST",
path: "http://localhost/foo",
wantCode: http.StatusOK,
},
{
title: "match DELETE handler",
router: router,
method: "DELETE",
path: "http://localhost/1/foo",
wantCode: http.StatusOK,
},
{
title: "match PUT handler",
router: router,
method: "PUT",
path: "http://localhost/1/foo",
wantCode: http.StatusOK,
},
{
title: "disallow PATCH method",
router: router,
method: "PATCH",
path: "http://localhost/1/foo",
wantCode: http.StatusMethodNotAllowed,
},
}
for _, test := range tests {
testMethodsSubrouter(t, test)
}
}
func ExampleSetURLVars() {
req, _ := http.NewRequest("GET", "/foo", nil)
req = SetURLVars(req, map[string]string{"foo": "bar"})
fmt.Println(Vars(req)["foo"])
// Output: bar
}
// testMethodsSubrouter runs an individual methodsSubrouterTest.
func testMethodsSubrouter(t *testing.T, test methodsSubrouterTest) {
// Execute request
req, _ := http.NewRequest(test.method, test.path, nil)
resp := NewRecorder()
test.router.ServeHTTP(resp, req)
switch test.wantCode {
case http.StatusMethodNotAllowed:
if resp.Code != http.StatusMethodNotAllowed {
t.Errorf(`(%s) Expected "405 Method Not Allowed", but got %d code`, test.title, resp.Code)
} else if matchedMethod := resp.Body.String(); matchedMethod != "" {
t.Errorf(`(%s) Expected "405 Method Not Allowed", but %q handler was called`, test.title, matchedMethod)
}
case http.StatusMovedPermanently:
if gotLocation := resp.HeaderMap.Get("Location"); gotLocation != test.redirectTo {
t.Errorf("(%s) Expected %q route-match to redirect to %q, but got %q", test.title, test.method, test.redirectTo, gotLocation)
}
case http.StatusOK:
if matchedMethod := resp.Body.String(); matchedMethod != test.method {
t.Errorf("(%s) Expected %q handler to be called, but %q handler was called", test.title, test.method, matchedMethod)
}
default:
expectedCodes := []int{http.StatusMethodNotAllowed, http.StatusMovedPermanently, http.StatusOK}
t.Errorf("(%s) Expected wantCode to be one of: %v, but got %d", test.title, expectedCodes, test.wantCode)
}
}
// mapToPairs converts a string map to a slice of string pairs
func mapToPairs(m map[string]string) []string {
var i int
@ -1994,6 +2315,14 @@ func stringMapEqual(m1, m2 map[string]string) bool {
return true
}
// stringHandler returns a handler func that writes a message 's' to the
// http.ResponseWriter.
func stringHandler(s string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(s))
}
}
// newRequest is a helper function to create a new request with a method and url.
// The request returned is a 'server' request as opposed to a 'client' one through
// simulated write onto the wire and read off of the wire.

View File

@ -681,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 {

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 {
if typ == regexpTypeQuery {
defaultPattern = ".*"
} else if matchHost {
} 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,16 +101,16 @@ 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('$')
}
reverse.WriteString(raw)
@ -118,15 +131,13 @@ 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,
}, nil
}
@ -135,15 +146,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 req.URL.EnscapedPath() 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.
@ -156,12 +162,12 @@ type routeRegexp struct {
// 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 {
if r.regexpType == regexpTypeQuery {
return r.matchQueryString(req)
}
path := req.URL.Path
if r.useEncodedPath {
if r.options.useEncodedPath {
path = req.URL.EscapedPath()
}
return r.regexp.MatchString(path)
@ -178,7 +184,7 @@ func (r *routeRegexp) url(values map[string]string) (string, error) {
if !ok {
return "", fmt.Errorf("mux: missing route variable %q", v)
}
if r.matchQuery {
if r.regexpType == regexpTypeQuery {
value = url.QueryEscape(value)
}
urlValues[k] = value
@ -203,7 +209,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]
@ -280,7 +286,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 {

View File

@ -43,6 +43,8 @@ type Route struct {
buildVarsFunc BuildVarsFunc
}
// SkipClean reports whether path cleaning is enabled for this route via
// Router.SkipClean.
func (r *Route) SkipClean() bool {
return r.skipClean
}
@ -75,6 +77,8 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
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.
@ -169,12 +173,12 @@ 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 typ == regexpTypePath || typ == regexpTypePrefix {
if len(tpl) > 0 && tpl[0] != '/' {
return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
}
@ -182,7 +186,10 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
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
}
@ -191,7 +198,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
@ -204,7 +211,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
@ -256,7 +263,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
@ -286,7 +294,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
}
@ -346,7 +354,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
}
@ -362,7 +370,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
}
@ -393,7 +401,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
}
}
@ -616,7 +624,7 @@ func (r *Route) GetPathRegexp() (string, error) {
// route queries.
// This is useful for building simple REST API documentation and for instrumentation
// against third-party services.
// An empty list will be returned if the route does not have queries.
// 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
@ -635,7 +643,7 @@ func (r *Route) GetQueriesRegexp() ([]string, error) {
// query matching.
// This is useful for building simple REST API documentation and for instrumentation
// against third-party services.
// An empty list will be returned if the route does not define queries.
// 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
@ -653,7 +661,7 @@ func (r *Route) GetQueriesTemplates() ([]string, error) {
// 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 empty list will be returned if route does not have methods.
// 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
@ -663,7 +671,7 @@ func (r *Route) GetMethods() ([]string, error) {
return []string(methods), nil
}
}
return nil, nil
return nil, errors.New("mux: route doesn't have methods")
}
// GetHostTemplate returns the template used to build the

19
gateway/vendor/github.com/gorilla/mux/test_helpers.go generated vendored 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)
}