updated dependencies

This commit is contained in:
ston1th 2018-09-20 00:18:46 +02:00
commit 62ff59957a
38 changed files with 915 additions and 304 deletions

View file

@ -25,7 +25,7 @@ golint:
$(GOPATH)/bin/golint . $(GOPATH)/bin/golint .
misspell: misspell:
$(GOPATH)/bin/misspell -i functionallity,avaliable,HALP,halp,agains,becuase,Christiaan,compatiblity,conjuction,frequence,inital,inot,occurance,overriden,pervious,preceeded,preceeds,precendence,PROPOGATE,reamining,represenation,soley,substract,supression,whcih * $(GOPATH)/bin/misspell -i functionallity,avaliable,HALP,halp,agains,becuase,Christiaan,compatiblity,conjuction,frequence,inital,inot,occurance,overriden,pervious,preceeded,preceeds,precendence,PROPOGATE,reamining,represenation,soley,substract,supression,whcih,preceed *
templates: templates:
$(CC) generate $(CC) generate

6
go.mod
View file

@ -1,8 +1,8 @@
module git.giftfish.de/ston1th/gowiki module git.giftfish.de/ston1th/gowiki
require ( require (
git.giftfish.de/ston1th/godrop v0.0.0-20170420131745-108583814ef5 git.giftfish.de/ston1th/godrop/v2 v2.0.1
git.giftfish.de/ston1th/jwt v0.0.0-20180913142945-4076e5cf1740 git.giftfish.de/ston1th/jwt/v3 v3.0.0
github.com/RoaringBitmap/roaring v0.4.16 // indirect github.com/RoaringBitmap/roaring v0.4.16 // indirect
github.com/Smerity/govarint v0.0.0-20150407073650-7265e41f48f1 // indirect github.com/Smerity/govarint v0.0.0-20150407073650-7265e41f48f1 // indirect
github.com/blevesearch/bleve v0.7.0 github.com/blevesearch/bleve v0.7.0
@ -24,7 +24,7 @@ require (
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c // indirect github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c // indirect
github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f // indirect github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f // indirect
github.com/gorilla/mux v1.3.0 github.com/gorilla/mux v1.6.2
github.com/jmhodges/levigo v0.0.0-20161115193449-c42d9e0ca023 // indirect github.com/jmhodges/levigo v0.0.0-20161115193449-c42d9e0ca023 // indirect
github.com/jtolds/gls v4.2.1+incompatible // indirect github.com/jtolds/gls v4.2.1+incompatible // indirect
github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae // indirect github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae // indirect

12
go.sum
View file

@ -1,7 +1,7 @@
git.giftfish.de/ston1th/godrop v0.0.0-20170420131745-108583814ef5 h1:uafvoLC59XDLlKutLaiBS0c0ZDn/OOjpKlRuefYan8w= git.giftfish.de/ston1th/godrop/v2 v2.0.1 h1:Ka7P1VcC11n4mDXhCA/qaM1Bi6IBhcGFk6J9OO6c2vs=
git.giftfish.de/ston1th/godrop v0.0.0-20170420131745-108583814ef5/go.mod h1:JdnYPhto248XT+uT1aH9CZrgJSYh50NTOJx8qEmIsOU= git.giftfish.de/ston1th/godrop/v2 v2.0.1/go.mod h1:QPMNHbTi2clDHyq8Chie49wFG78LkwKnw5lkx/RBkKQ=
git.giftfish.de/ston1th/jwt v0.0.0-20180913142945-4076e5cf1740 h1:IHG3U1lPYpwDzhnh2CXhQDmWA/D6G6auOHnLmWOoLyg= git.giftfish.de/ston1th/jwt/v3 v3.0.0 h1:zywHtrYmEpU+osig6ujvHdettLuuDC4K7HHaiGigD/k=
git.giftfish.de/ston1th/jwt v0.0.0-20180913142945-4076e5cf1740/go.mod h1:68kBYmlHflbQbc1AX4by9daoxI3zV6sSow765JeFRqw= git.giftfish.de/ston1th/jwt/v3 v3.0.0/go.mod h1:jDALrW7OKeIaqYuMxs3GWyPRnQZmk/R+Lu9p/Em3Ziw=
github.com/RoaringBitmap/roaring v0.4.16 h1:NholfewybRLOwACgfqfzn/N5xa6keKNs4fP00t0cwLo= github.com/RoaringBitmap/roaring v0.4.16 h1:NholfewybRLOwACgfqfzn/N5xa6keKNs4fP00t0cwLo=
github.com/RoaringBitmap/roaring v0.4.16/go.mod h1:8khRDP4HmeXns4xIj9oGrKSz7XTQiJx2zgh7AcNke4w= github.com/RoaringBitmap/roaring v0.4.16/go.mod h1:8khRDP4HmeXns4xIj9oGrKSz7XTQiJx2zgh7AcNke4w=
github.com/Smerity/govarint v0.0.0-20150407073650-7265e41f48f1 h1:G/NOANWMQev0CftoyxQwtRakdyNNNMB3qxkt/tj1HGs= github.com/Smerity/govarint v0.0.0-20150407073650-7265e41f48f1 h1:G/NOANWMQev0CftoyxQwtRakdyNNNMB3qxkt/tj1HGs=
@ -48,8 +48,8 @@ github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c h1:16eHWuMGvCjSf
github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f h1:9oNbS1z4rVpbnkHBdPZU4jo9bSmrLpII768arSyMFgk= github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f h1:9oNbS1z4rVpbnkHBdPZU4jo9bSmrLpII768arSyMFgk=
github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
github.com/gorilla/mux v1.3.0 h1:HwSEKGN6U5T2aAQTfu5pW8fiwjSp3IgwdRbkICydk/c= github.com/gorilla/mux v1.6.2 h1:Pgr17XVTNXAk3q/r4CpKzC5xBM/qW1uVLV+IhRZpIIk=
github.com/gorilla/mux v1.3.0/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jmhodges/levigo v0.0.0-20161115193449-c42d9e0ca023 h1:y5P5G9cANJZt3MXlMrgELo5mNLZPXH8aGFFFG7IzPU0= github.com/jmhodges/levigo v0.0.0-20161115193449-c42d9e0ca023 h1:y5P5G9cANJZt3MXlMrgELo5mNLZPXH8aGFFFG7IzPU0=

View file

@ -3,7 +3,10 @@
package cmd package cmd
import ( import (
"git.giftfish.de/ston1th/godrop" "git.giftfish.de/ston1th/godrop/v2"
"git.giftfish.de/ston1th/gowiki/pkg/core"
"git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/gowiki/pkg/server"
"github.com/urfave/cli" "github.com/urfave/cli"
stdlog "log" stdlog "log"
"net" "net"
@ -11,10 +14,6 @@ import (
"os/signal" "os/signal"
"syscall" "syscall"
"time" "time"
"git.giftfish.de/ston1th/gowiki/pkg/core"
"git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/gowiki/pkg/server"
) )
const ( const (

View file

@ -4,11 +4,10 @@ package index
import ( import (
"fmt" "fmt"
"html/template"
"os"
"git.giftfish.de/ston1th/gowiki/pkg/core" "git.giftfish.de/ston1th/gowiki/pkg/core"
"github.com/blevesearch/bleve" "github.com/blevesearch/bleve"
"html/template"
"os"
) )
const maxSearchResult = 101 const maxSearchResult = 101

View file

@ -3,15 +3,14 @@
package render package render
import ( import (
"html/template"
"regexp"
"strconv"
"strings"
"git.giftfish.de/ston1th/gowiki/pkg/core" "git.giftfish.de/ston1th/gowiki/pkg/core"
"github.com/blevesearch/bleve/analysis" "github.com/blevesearch/bleve/analysis"
"github.com/blevesearch/bleve/analysis/char/html" "github.com/blevesearch/bleve/analysis/char/html"
"github.com/russross/blackfriday" "github.com/russross/blackfriday"
"html/template"
"regexp"
"strconv"
"strings"
) )
var filter = makeFilter() var filter = makeFilter()

View file

@ -5,7 +5,7 @@ package server
import ( import (
"errors" "errors"
"git.giftfish.de/ston1th/gowiki/pkg/log" "git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/jwt" "git.giftfish.de/ston1th/jwt/v3"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"html/template" "html/template"
"net/http" "net/http"

View file

@ -6,7 +6,7 @@ import (
"git.giftfish.de/ston1th/gowiki/pkg/core" "git.giftfish.de/ston1th/gowiki/pkg/core"
"git.giftfish.de/ston1th/gowiki/pkg/log" "git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/gowiki/pkg/render" "git.giftfish.de/ston1th/gowiki/pkg/render"
"git.giftfish.de/ston1th/jwt" "git.giftfish.de/ston1th/jwt/v3"
"net/http" "net/http"
"time" "time"
) )

View file

@ -5,16 +5,15 @@ package server
import ( import (
"bytes" "bytes"
"context" "context"
"git.giftfish.de/ston1th/gowiki/pkg/core"
"git.giftfish.de/ston1th/gowiki/pkg/db"
"git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/jwt/v3"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"html/template" "html/template"
"net" "net"
"net/http" "net/http"
"time" "time"
"git.giftfish.de/ston1th/gowiki/pkg/core"
"git.giftfish.de/ston1th/gowiki/pkg/db"
"git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/jwt"
) )
const ( const (

View file

@ -7,7 +7,7 @@ import (
"crypto/subtle" "crypto/subtle"
"encoding/base64" "encoding/base64"
"git.giftfish.de/ston1th/gowiki/pkg/log" "git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/jwt" "git.giftfish.de/ston1th/jwt/v3"
) )
const keySize = jwt.KeySize / 2 const keySize = jwt.KeySize / 2

View file

@ -2,9 +2,7 @@
package store package store
import ( import "fmt"
"fmt"
)
func storeErr(i interface{}) error { func storeErr(i interface{}) error {
return fmt.Errorf("store: %s", i) return fmt.Errorf("store: %s", i)

View file

@ -1,23 +0,0 @@
// Copyright (C) 2017 Marius Schellenberger
// +build cgo
package godrop
import "os/user"
func lookupUID(username string) (string, error) {
u, err := user.Lookup(username)
if err != nil {
return "", err
}
return u.Uid, err
}
func lookupGID(name string) (string, error) {
g, err := user.LookupGroup(name)
if err != nil {
return "", err
}
return g.Gid, err
}

View file

@ -1,43 +0,0 @@
// Copyright (C) 2017 Marius Schellenberger
// +build darwin dragonfly freebsd android linux netbsd openbsd solaris
// +build !cgo
package godrop
import (
"io/ioutil"
"os"
"regexp"
)
func readFile(name, file string) (id string, err error) {
id = "-1"
if name == "" {
return
}
f, err := os.Open(file)
if err != nil {
return
}
b, err := ioutil.ReadAll(f)
if err != nil {
return
}
r := regexp.MustCompile(name + `:.*?:(\d+):`)
m := r.FindAllStringSubmatch(string(b), 1)
if len(m) == 1 {
if len(m[0]) == 2 {
return m[0][1], nil
}
}
return
}
func lookupUID(username string) (string, error) {
return readFile(username, "/etc/passwd")
}
func lookupGID(name string) (string, error) {
return readFile(name, "/etc/group")
}

View file

@ -1,2 +1,3 @@
port80 port80
port80fg
port80and443 port80and443

View file

@ -0,0 +1 @@
module git.giftfish.de/ston1th/godrop/v2

View file

@ -1,10 +1,11 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2018 Marius Schellenberger
// +build go1.11
// Package godrop provides a simple privileges dropping library // Package godrop provides a simple privileges dropping library
package godrop package godrop
import ( import (
"errors"
"fmt" "fmt"
"net" "net"
"os" "os"
@ -13,8 +14,8 @@ import (
"syscall" "syscall"
) )
func errf(err error) error { func errf(i interface{}) error {
return fmt.Errorf("godrop: %s", err) return fmt.Errorf("godrop: %s", i)
} }
// Config represents the drop config // Config represents the drop config
@ -45,7 +46,7 @@ func MultiDrop(c Config, f func() ([]net.Listener, error)) error {
return errf(err) return errf(err)
} }
if uid == 0 { if uid == 0 {
return errf(errors.New("unable to drop privileges to uid 0 (root)")) return errf("unable to drop privileges to uid 0 (root)")
} }
gid, err := groupID(c.Group) gid, err := groupID(c.Group)
if err != nil { if err != nil {
@ -68,20 +69,14 @@ func MultiDrop(c Config, f func() ([]net.Listener, error)) error {
f, err = l.File() f, err = l.File()
l.Close() l.Close()
default: default:
return errf(fmt.Errorf("index: %d listener is not type of either *net.TCPListener or *net.UnixListener", i)) return errf(fmt.Sprintf("index %d listener is not type of either *net.TCPListener or *net.UnixListener", i))
} }
if err != nil { if err != nil {
return errf(fmt.Errorf("index: %d %s", i, err)) return errf(fmt.Sprintf("index %d %s", i, err))
} }
cmd.ExtraFiles = append(cmd.ExtraFiles, f) cmd.ExtraFiles = append(cmd.ExtraFiles, f)
} }
if c.Foreground {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
cmd.SysProcAttr = &syscall.SysProcAttr{ cmd.SysProcAttr = &syscall.SysProcAttr{
Chroot: c.Chroot, Chroot: c.Chroot,
Credential: &syscall.Credential{ Credential: &syscall.Credential{
@ -91,16 +86,31 @@ func MultiDrop(c Config, f func() ([]net.Listener, error)) error {
Setsid: true, Setsid: true,
} }
if c.Foreground {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
return errf(err) return errf(err)
} }
if c.Foreground { if c.Foreground {
go func() { go func() {
term := make(chan os.Signal)
signal.Notify(term, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
sigs := make(chan os.Signal) sigs := make(chan os.Signal)
signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) signal.Notify(sigs, syscall.SIGSTOP, syscall.SIGCONT, syscall.SIGUSR1, syscall.SIGUSR2)
sig := <-sigs for {
cmd.Process.Signal(sig) select {
case sig := <-term:
cmd.Process.Signal(sig)
return
case sig := <-sigs:
cmd.Process.Signal(sig)
}
}
}() }()
_ = cmd.Wait() _ = cmd.Wait()
os.Exit(int(cmd.ProcessState.Sys().(syscall.WaitStatus))) os.Exit(int(cmd.ProcessState.Sys().(syscall.WaitStatus)))
@ -110,7 +120,7 @@ func MultiDrop(c Config, f func() ([]net.Listener, error)) error {
case uid: case uid:
return nil return nil
} }
return errf(errors.New("dropping priviledges failed")) return errf("dropping priviledges failed")
} }
// GetListener returns the listener socket of file descriptor 3 // GetListener returns the listener socket of file descriptor 3
@ -120,6 +130,9 @@ func GetListener() (net.Listener, error) {
// GetListenerFd returns the listener socket of the given file descriptor // GetListenerFd returns the listener socket of the given file descriptor
func GetListenerFd(fd int) (net.Listener, error) { func GetListenerFd(fd int) (net.Listener, error) {
if fd < 3 {
return nil, errf("fd is less than 3")
}
f := os.NewFile(uintptr(fd), "") f := os.NewFile(uintptr(fd), "")
defer f.Close() defer f.Close()
return net.FileListener(f) return net.FileListener(f)

View file

@ -1,8 +1,13 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2018 Marius Schellenberger
// +build go1.11
package godrop package godrop
import "strconv" import (
"os/user"
"strconv"
)
func atoi(a string) (int, error) { func atoi(a string) (int, error) {
i, err := strconv.Atoi(a) i, err := strconv.Atoi(a)
@ -12,18 +17,18 @@ func atoi(a string) (int, error) {
return i, nil return i, nil
} }
func userID(username string) (uid int, err error) { func userID(username string) (int, error) {
id, err := lookupUID(username) u, err := user.Lookup(username)
if err != nil { if err != nil {
return -1, err return -1, err
} }
return atoi(id) return atoi(u.Uid)
} }
func groupID(name string) (int, error) { func groupID(name string) (int, error) {
id, err := lookupGID(name) g, err := user.LookupGroup(name)
if err != nil { if err != nil {
return -1, err return -1, err
} }
return atoi(id) return atoi(g.Gid)
} }

View file

@ -0,0 +1 @@
module git.giftfish.de/ston1th/jwt/v3

View file

@ -3,12 +3,14 @@ sudo: false
matrix: matrix:
include: include:
- go: 1.2 - go: 1.5.x
- go: 1.3 - go: 1.6.x
- go: 1.4 - go: 1.7.x
- go: 1.5 - go: 1.8.x
- go: 1.6 - go: 1.9.x
- go: 1.7 - go: 1.10.x
- go: tip
allow_failures:
- go: tip - go: tip
install: install:

11
vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md generated vendored Normal file
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,7 +1,8 @@
gorilla/mux # gorilla/mux
===
[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/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) [![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)
![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png) ![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png)
@ -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`. * 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. * 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. * 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. * 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,12 @@ The name mux stands for "HTTP request multiplexer". Like the standard `http.Serv
* [Install](#install) * [Install](#install)
* [Examples](#examples) * [Examples](#examples)
* [Matching Routes](#matching-routes) * [Matching Routes](#matching-routes)
* [Listing Routes](#listing-routes)
* [Static Files](#static-files) * [Static Files](#static-files)
* [Registered URLs](#registered-urls) * [Registered URLs](#registered-urls)
* [Walking Routes](#walking-routes)
* [Graceful Shutdown](#graceful-shutdown)
* [Middleware](#middleware)
* [Testing Handlers](#testing-handlers)
* [Full Example](#full-example) * [Full Example](#full-example)
--- ---
@ -44,11 +48,11 @@ Let's start registering a couple of URL paths and handlers:
```go ```go
func main() { func main() {
r := mux.NewRouter() r := mux.NewRouter()
r.HandleFunc("/", HomeHandler) r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler) r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r) http.Handle("/", r)
} }
``` ```
@ -67,9 +71,9 @@ The names are used to create a map of route variables which can be retrieved cal
```go ```go
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) { func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"]) fmt.Fprintf(w, "Category: %v\n", vars["category"])
} }
``` ```
@ -121,7 +125,7 @@ r.Queries("key", "value")
```go ```go
r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
return r.ProtoMajor == 0 return r.ProtoMajor == 0
}) })
``` ```
@ -134,6 +138,14 @@ r.HandleFunc("/products", ProductsHandler).
Schemes("http") 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". 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: 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,68 +180,33 @@ s.HandleFunc("/{key}/", ProductHandler)
s.HandleFunc("/{key}/details", ProductDetailsHandler) 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 ### Static Files
Note that the path provided to `PathPrefix()` represents a "wildcard": calling Note that the path provided to `PathPrefix()` represents a "wildcard": calling
`PathPrefix("/static/").Handler(...)` means that the handler will be passed any `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 ```go
func main() { func main() {
var dir string var dir string
flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
flag.Parse() flag.Parse()
r := mux.NewRouter() r := mux.NewRouter()
// This will serve files under http://localhost:8000/static/<filename> // This will serve files under http://localhost:8000/static/<filename>
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
srv := &http.Server{ srv := &http.Server{
Handler: r, Handler: r,
Addr: "127.0.0.1:8000", Addr: "127.0.0.1:8000",
// Good practice: enforce timeouts for servers you create! // Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second,
} }
log.Fatal(srv.ListenAndServe()) log.Fatal(srv.ListenAndServe())
} }
``` ```
@ -257,19 +234,21 @@ url, err := r.Get("article").URL("category", "technology", "id", "42")
"/articles/technology/42" "/articles/technology/42"
``` ```
This also works for host variables: This also works for host and query value variables:
```go ```go
r := mux.NewRouter() r := mux.NewRouter()
r.Host("{subdomain}.domain.com"). r.Host("{subdomain}.domain.com").
Path("/articles/{category}/{id:[0-9]+}"). Path("/articles/{category}/{id:[0-9]+}").
Queries("filter", "{filter}").
HandlerFunc(ArticleHandler). HandlerFunc(ArticleHandler).
Name("article") 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", url, err := r.Get("article").URL("subdomain", "news",
"category", "technology", "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. 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.
@ -307,6 +286,337 @@ url, err := r.Get("article").URL("subdomain", "news",
"id", "42") "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.
### 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 {
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 ## Full Example
Here's a complete, runnable example of a small `mux` based server: Here's a complete, runnable example of a small `mux` based server:
@ -315,22 +625,22 @@ Here's a complete, runnable example of a small `mux` based server:
package main package main
import ( import (
"net/http" "net/http"
"log" "log"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
func YourHandler(w http.ResponseWriter, r *http.Request) { func YourHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Gorilla!\n")) w.Write([]byte("Gorilla!\n"))
} }
func main() { func main() {
r := mux.NewRouter() r := mux.NewRouter()
// Routes consist of a path and a handler function. // Routes consist of a path and a handler function.
r.HandleFunc("/", YourHandler) r.HandleFunc("/", YourHandler)
// Bind to a port and pass our router in // Bind to a port and pass our router in
log.Fatal(http.ListenAndServe(":8000", r)) log.Fatal(http.ListenAndServe(":8000", r))
} }
``` ```

76
vendor/github.com/gorilla/mux/doc.go generated vendored
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, * Requests can be matched based on URL host, path, path prefix, schemes,
header and query values, HTTP methods or using custom matchers. header and query values, HTTP methods or using custom matchers.
* URL hosts and paths can have variables with an optional regular * URL hosts, paths and query values can have variables with an optional
expression. regular expression.
* Registered URLs can be built, or "reversed", which helps maintaining * Registered URLs can be built, or "reversed", which helps maintaining
references to resources. references to resources.
* Routes can be used as subrouters: nested routes are only tested if the * 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" "/articles/technology/42"
This also works for host variables: This also works for host and query value variables:
r := mux.NewRouter() r := mux.NewRouter()
r.Host("{subdomain}.domain.com"). r.Host("{subdomain}.domain.com").
Path("/articles/{category}/{id:[0-9]+}"). Path("/articles/{category}/{id:[0-9]+}").
Queries("filter", "{filter}").
HandlerFunc(ArticleHandler). HandlerFunc(ArticleHandler).
Name("article") 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", url, err := r.Get("article").URL("subdomain", "news",
"category", "technology", "category", "technology",
"id", "42") "id", "42",
"filter", "gorilla")
All variables defined in the route are required, and their values must All variables defined in the route are required, and their values must
conform to the corresponding patterns. These requirements guarantee that a conform to the corresponding patterns. These requirements guarantee that a
@ -236,5 +238,69 @@ as well:
url, err := r.Get("article").URL("subdomain", "news", url, err := r.Get("article").URL("subdomain", "news",
"category", "technology", "category", "technology",
"id", "42") "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 package mux

72
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)
})
}
}

116
vendor/github.com/gorilla/mux/mux.go generated vendored
View file

@ -10,7 +10,14 @@ import (
"net/http" "net/http"
"path" "path"
"regexp" "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. // NewRouter returns a new router instance.
@ -39,6 +46,10 @@ func NewRouter() *Router {
type Router struct { type Router struct {
// Configurable Handler to be used when no route matches. // Configurable Handler to be used when no route matches.
NotFoundHandler http.Handler NotFoundHandler http.Handler
// Configurable Handler to be used when the request method does not match the route.
MethodNotAllowedHandler http.Handler
// Parent route, if this is a subrouter. // Parent route, if this is a subrouter.
parent parentRoute parent parentRoute
// Routes to be matched, in order. // Routes to be matched, in order.
@ -55,21 +66,51 @@ type Router struct {
KeepContext bool KeepContext bool
// see Router.UseEncodedPath(). This defines a flag for all routes. // see Router.UseEncodedPath(). This defines a flag for all routes.
useEncodedPath bool useEncodedPath bool
// Slice of middlewares to be called after a match is found
middlewares []middleware
} }
// Match matches registered routes against the request. // 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 { func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
for _, route := range r.routes { for _, route := range r.routes {
if route.Match(req, match) { 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 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) // Closest match for a router (includes sub-routers)
if r.NotFoundHandler != nil { if r.NotFoundHandler != nil {
match.Handler = r.NotFoundHandler match.Handler = r.NotFoundHandler
match.MatchErr = ErrNotFound
return true return true
} }
match.MatchErr = ErrNotFound
return false return false
} }
@ -81,7 +122,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if !r.skipClean { if !r.skipClean {
path := req.URL.Path path := req.URL.Path
if r.useEncodedPath { if r.useEncodedPath {
path = getPath(req) path = req.URL.EscapedPath()
} }
// Clean path to canonical form and redirect. // Clean path to canonical form and redirect.
if p := cleanPath(path); p != path { if p := cleanPath(path); p != path {
@ -105,12 +146,19 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
req = setVars(req, match.Vars) req = setVars(req, match.Vars)
req = setCurrentRoute(req, match.Route) req = setCurrentRoute(req, match.Route)
} }
if handler == nil && match.MatchErr == ErrMethodMismatch {
handler = methodNotAllowedHandler()
}
if handler == nil { if handler == nil {
handler = http.NotFoundHandler() handler = http.NotFoundHandler()
} }
if !r.KeepContext { if !r.KeepContext {
defer contextClear(req) defer contextClear(req)
} }
handler.ServeHTTP(w, req) handler.ServeHTTP(w, req)
} }
@ -128,13 +176,18 @@ func (r *Router) GetRoute(name string) *Route {
// StrictSlash defines the trailing slash behavior for new routes. The initial // StrictSlash defines the trailing slash behavior for new routes. The initial
// value is false. // 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 // to the former and vice versa. In other words, your application will always
// see the path as specified in the route. // see the path as specified in the route.
// //
// When false, if the route path is "/path", accessing "/path/" will not match // When false, if the route path is "/path", accessing "/path/" will not match
// this route and vice versa. // 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, // 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 // 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 // be determined from a prefix alone. However, any subrouters created from that
@ -160,10 +213,6 @@ func (r *Router) SkipClean(value bool) *Router {
// UseEncodedPath tells the router to match the encoded original path // UseEncodedPath tells the router to match the encoded original path
// to the routes. // to the routes.
// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to". // 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. // 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" // For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
@ -176,6 +225,13 @@ func (r *Router) UseEncodedPath() *Router {
// parentRoute // parentRoute
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
func (r *Router) getBuildScheme() string {
if r.parent != nil {
return r.parent.getBuildScheme()
}
return ""
}
// getNamedRoutes returns the map where named routes are registered. // getNamedRoutes returns the map where named routes are registered.
func (r *Router) getNamedRoutes() map[string]*Route { func (r *Router) getNamedRoutes() map[string]*Route {
if r.namedRoutes == nil { if r.namedRoutes == nil {
@ -299,10 +355,6 @@ type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
for _, t := range r.routes { for _, t := range r.routes {
if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" {
continue
}
err := walkFn(t, r, ancestors) err := walkFn(t, r, ancestors)
if err == SkipRouter { if err == SkipRouter {
continue continue
@ -312,10 +364,12 @@ func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
} }
for _, sr := range t.matchers { for _, sr := range t.matchers {
if h, ok := sr.(*Router); ok { if h, ok := sr.(*Router); ok {
ancestors = append(ancestors, t)
err := h.walk(walkFn, ancestors) err := h.walk(walkFn, ancestors)
if err != nil { if err != nil {
return err return err
} }
ancestors = ancestors[:len(ancestors)-1]
} }
} }
if h, ok := t.handler.(*Router); ok { if h, ok := t.handler.(*Router); ok {
@ -339,6 +393,11 @@ type RouteMatch struct {
Route *Route Route *Route
Handler http.Handler Handler http.Handler
Vars map[string]string 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 type contextKey int
@ -380,28 +439,6 @@ func setCurrentRoute(r *http.Request, val interface{}) *http.Request {
// Helpers // 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. // cleanPath returns the canonical path for p, eliminating . and .. elements.
// Borrowed from the net/http package. // Borrowed from the net/http package.
func cleanPath(p string) string { func cleanPath(p string) string {
@ -458,7 +495,7 @@ func mapFromPairsToString(pairs ...string) (map[string]string, error) {
return m, nil return m, nil
} }
// mapFromPairsToRegex converts variadic string paramers to a // mapFromPairsToRegex converts variadic string parameters to a
// string to regex map. // string to regex map.
func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
length, err := checkPairs(pairs...) length, err := checkPairs(pairs...)
@ -540,3 +577,12 @@ func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]s
} }
return true 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) }

View file

@ -14,6 +14,20 @@ import (
"strings" "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, // newRouteRegexp parses a route template and returns a routeRegexp,
// used to match a host, a path or a query string. // 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 // Previously we accepted only Python-like identifiers for variable
// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that // 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. // 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. // Check if it is well-formed.
idxs, errBraces := braceIndices(tpl) idxs, errBraces := braceIndices(tpl)
if errBraces != nil { if errBraces != nil {
@ -34,19 +48,18 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
template := tpl template := tpl
// Now let's parse it. // Now let's parse it.
defaultPattern := "[^/]+" defaultPattern := "[^/]+"
if matchQuery { if typ == regexpTypeQuery {
defaultPattern = "[^?&]*" defaultPattern = ".*"
} else if matchHost { } else if typ == regexpTypeHost {
defaultPattern = "[^.]+" defaultPattern = "[^.]+"
matchPrefix = false
} }
// Only match strict slash if not matching // Only match strict slash if not matching
if matchPrefix || matchHost || matchQuery { if typ != regexpTypePath {
strictSlash = false options.strictSlash = false
} }
// Set a flag for strictSlash. // Set a flag for strictSlash.
endSlash := false endSlash := false
if strictSlash && strings.HasSuffix(tpl, "/") { if options.strictSlash && strings.HasSuffix(tpl, "/") {
tpl = tpl[:len(tpl)-1] tpl = tpl[:len(tpl)-1]
endSlash = true endSlash = true
} }
@ -88,16 +101,16 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
// Add the remaining. // Add the remaining.
raw := tpl[end:] raw := tpl[end:]
pattern.WriteString(regexp.QuoteMeta(raw)) pattern.WriteString(regexp.QuoteMeta(raw))
if strictSlash { if options.strictSlash {
pattern.WriteString("[/]?") pattern.WriteString("[/]?")
} }
if matchQuery { if typ == regexpTypeQuery {
// Add the default pattern if the query value is empty // Add the default pattern if the query value is empty
if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
pattern.WriteString(defaultPattern) pattern.WriteString(defaultPattern)
} }
} }
if !matchPrefix { if typ != regexpTypePrefix {
pattern.WriteByte('$') pattern.WriteByte('$')
} }
reverse.WriteString(raw) reverse.WriteString(raw)
@ -118,15 +131,13 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
// Done! // Done!
return &routeRegexp{ return &routeRegexp{
template: template, template: template,
matchHost: matchHost, regexpType: typ,
matchQuery: matchQuery, options: options,
strictSlash: strictSlash, regexp: reg,
useEncodedPath: useEncodedPath, reverse: reverse.String(),
regexp: reg, varsN: varsN,
reverse: reverse.String(), varsR: varsR,
varsN: varsN,
varsR: varsR,
}, nil }, nil
} }
@ -135,15 +146,10 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
type routeRegexp struct { type routeRegexp struct {
// The unmodified template. // The unmodified template.
template string template string
// True for host match, false for path or query string match. // The type of match
matchHost bool regexpType regexpType
// True for query string match, false for path and host match. // Options for matching
matchQuery bool options routeRegexpOptions
// 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
// Expanded regexp. // Expanded regexp.
regexp *regexp.Regexp regexp *regexp.Regexp
// Reverse template. // Reverse template.
@ -156,13 +162,13 @@ type routeRegexp struct {
// Match matches the regexp against the URL host or path. // Match matches the regexp against the URL host or path.
func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
if !r.matchHost { if r.regexpType != regexpTypeHost {
if r.matchQuery { if r.regexpType == regexpTypeQuery {
return r.matchQueryString(req) return r.matchQueryString(req)
} }
path := req.URL.Path path := req.URL.Path
if r.useEncodedPath { if r.options.useEncodedPath {
path = getPath(req) path = req.URL.EscapedPath()
} }
return r.regexp.MatchString(path) return r.regexp.MatchString(path)
} }
@ -178,6 +184,9 @@ func (r *routeRegexp) url(values map[string]string) (string, error) {
if !ok { if !ok {
return "", fmt.Errorf("mux: missing route variable %q", v) return "", fmt.Errorf("mux: missing route variable %q", v)
} }
if r.regexpType == regexpTypeQuery {
value = url.QueryEscape(value)
}
urlValues[k] = value urlValues[k] = value
} }
rv := fmt.Sprintf(r.reverse, urlValues...) rv := fmt.Sprintf(r.reverse, urlValues...)
@ -200,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 // For a URL with foo=bar&baz=ding, we return only the relevant key
// value pair for the routeRegexp. // value pair for the routeRegexp.
func (r *routeRegexp) getURLQuery(req *http.Request) string { func (r *routeRegexp) getURLQuery(req *http.Request) string {
if !r.matchQuery { if r.regexpType != regexpTypeQuery {
return "" return ""
} }
templateKey := strings.SplitN(r.template, "=", 2)[0] templateKey := strings.SplitN(r.template, "=", 2)[0]
@ -269,7 +278,7 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
} }
path := req.URL.Path path := req.URL.Path
if r.useEncodedPath { if r.useEncodedPath {
path = getPath(req) path = req.URL.EscapedPath()
} }
// Store path variables. // Store path variables.
if v.path != nil { if v.path != nil {
@ -277,7 +286,7 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
if len(matches) > 0 { if len(matches) > 0 {
extractVars(path, matches, v.path.varsN, m.Vars) extractVars(path, matches, v.path.varsN, m.Vars)
// Check if we should redirect. // Check if we should redirect.
if v.path.strictSlash { if v.path.options.strictSlash {
p1 := strings.HasSuffix(path, "/") p1 := strings.HasSuffix(path, "/")
p2 := strings.HasSuffix(v.path.template, "/") p2 := strings.HasSuffix(v.path.template, "/")
if p1 != p2 { if p1 != p2 {

View file

@ -31,6 +31,8 @@ type Route struct {
skipClean bool skipClean bool
// If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to" // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
useEncodedPath bool useEncodedPath bool
// The scheme used when building URLs.
buildScheme string
// If true, this route never matches: it is only used to build URLs. // If true, this route never matches: it is only used to build URLs.
buildOnly bool buildOnly bool
// The name used to build URLs. // The name used to build URLs.
@ -41,6 +43,8 @@ type Route struct {
buildVarsFunc BuildVarsFunc buildVarsFunc BuildVarsFunc
} }
// SkipClean reports whether path cleaning is enabled for this route via
// Router.SkipClean.
func (r *Route) SkipClean() bool { func (r *Route) SkipClean() bool {
return r.skipClean return r.skipClean
} }
@ -50,12 +54,33 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
if r.buildOnly || r.err != nil { if r.buildOnly || r.err != nil {
return false return false
} }
var matchErr error
// Match everything. // Match everything.
for _, m := range r.matchers { for _, m := range r.matchers {
if matched := m.Match(req, match); !matched { if matched := m.Match(req, match); !matched {
if _, ok := m.(methodMatcher); ok {
matchErr = ErrMethodMismatch
continue
}
matchErr = nil
return false 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. // Yay, we have a match. Let's collect some info about it.
if match.Route == nil { if match.Route == nil {
match.Route = r match.Route = r
@ -66,6 +91,7 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
if match.Vars == nil { if match.Vars == nil {
match.Vars = make(map[string]string) match.Vars = make(map[string]string)
} }
// Set variables. // Set variables.
if r.regexp != nil { if r.regexp != nil {
r.regexp.setMatch(req, match, r) r.regexp.setMatch(req, match, r)
@ -147,20 +173,23 @@ func (r *Route) addMatcher(m matcher) *Route {
} }
// addRegexpMatcher adds a host or path matcher and builder to a 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 { if r.err != nil {
return r.err return r.err
} }
r.regexp = r.getRegexpGroup() r.regexp = r.getRegexpGroup()
if !matchHost && !matchQuery { if typ == regexpTypePath || typ == regexpTypePrefix {
if tpl == "/" && (len(tpl) == 0 || tpl[0] != '/') { if len(tpl) > 0 && tpl[0] != '/' {
return fmt.Errorf("mux: path must start with a slash, got %q", tpl) return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
} }
if r.regexp.path != nil { if r.regexp.path != nil {
tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl 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 { if err != nil {
return err return err
} }
@ -169,7 +198,7 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
return err return err
} }
} }
if matchHost { if typ == regexpTypeHost {
if r.regexp.path != nil { if r.regexp.path != nil {
if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil {
return err return err
@ -182,7 +211,7 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
return err return err
} }
} }
if matchQuery { if typ == regexpTypeQuery {
r.regexp.queries = append(r.regexp.queries, rr) r.regexp.queries = append(r.regexp.queries, rr)
} else { } else {
r.regexp.path = rr r.regexp.path = rr
@ -234,7 +263,8 @@ func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
// "X-Requested-With", "XMLHttpRequest") // "X-Requested-With", "XMLHttpRequest")
// //
// The above route will only match if both the request header matches both regular expressions. // 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 { func (r *Route) HeadersRegexp(pairs ...string) *Route {
if r.err == nil { if r.err == nil {
var headers map[string]*regexp.Regexp var headers map[string]*regexp.Regexp
@ -264,7 +294,7 @@ func (r *Route) HeadersRegexp(pairs ...string) *Route {
// Variable names must be unique in a given route. They can be retrieved // Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request). // calling mux.Vars(request).
func (r *Route) Host(tpl string) *Route { func (r *Route) Host(tpl string) *Route {
r.err = r.addRegexpMatcher(tpl, true, false, false) r.err = r.addRegexpMatcher(tpl, regexpTypeHost)
return r return r
} }
@ -324,7 +354,7 @@ func (r *Route) Methods(methods ...string) *Route {
// Variable names must be unique in a given route. They can be retrieved // Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request). // calling mux.Vars(request).
func (r *Route) Path(tpl string) *Route { func (r *Route) Path(tpl string) *Route {
r.err = r.addRegexpMatcher(tpl, false, false, false) r.err = r.addRegexpMatcher(tpl, regexpTypePath)
return r return r
} }
@ -340,7 +370,7 @@ func (r *Route) Path(tpl string) *Route {
// Also note that the setting of Router.StrictSlash() has no effect on routes // Also note that the setting of Router.StrictSlash() has no effect on routes
// with a PathPrefix matcher. // with a PathPrefix matcher.
func (r *Route) PathPrefix(tpl string) *Route { func (r *Route) PathPrefix(tpl string) *Route {
r.err = r.addRegexpMatcher(tpl, false, true, false) r.err = r.addRegexpMatcher(tpl, regexpTypePrefix)
return r return r
} }
@ -371,7 +401,7 @@ func (r *Route) Queries(pairs ...string) *Route {
return nil return nil
} }
for i := 0; i < length; i += 2 { 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 return r
} }
} }
@ -394,6 +424,9 @@ func (r *Route) Schemes(schemes ...string) *Route {
for k, v := range schemes { for k, v := range schemes {
schemes[k] = strings.ToLower(v) schemes[k] = strings.ToLower(v)
} }
if r.buildScheme == "" && len(schemes) > 0 {
r.buildScheme = schemes[0]
}
return r.addMatcher(schemeMatcher(schemes)) return r.addMatcher(schemeMatcher(schemes))
} }
@ -477,22 +510,33 @@ func (r *Route) URL(pairs ...string) (*url.URL, error) {
return nil, err return nil, err
} }
var scheme, host, path string var scheme, host, path string
queries := make([]string, 0, len(r.regexp.queries))
if r.regexp.host != nil { if r.regexp.host != nil {
// Set a default scheme.
scheme = "http"
if host, err = r.regexp.host.url(values); err != nil { if host, err = r.regexp.host.url(values); err != nil {
return nil, err return nil, err
} }
scheme = "http"
if s := r.getBuildScheme(); s != "" {
scheme = s
}
} }
if r.regexp.path != nil { if r.regexp.path != nil {
if path, err = r.regexp.path.url(values); err != nil { if path, err = r.regexp.path.url(values); err != nil {
return nil, err 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{ return &url.URL{
Scheme: scheme, Scheme: scheme,
Host: host, Host: host,
Path: path, Path: path,
RawQuery: strings.Join(queries, "&"),
}, nil }, nil
} }
@ -514,10 +558,14 @@ func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &url.URL{ u := &url.URL{
Scheme: "http", Scheme: "http",
Host: host, Host: host,
}, nil }
if s := r.getBuildScheme(); s != "" {
u.Scheme = s
}
return u, nil
} }
// URLPath builds the path part of the URL for a route. See Route.URL(). // URLPath builds the path part of the URL for a route. See Route.URL().
@ -558,6 +606,74 @@ func (r *Route) GetPathTemplate() (string, error) {
return r.regexp.path.template, nil 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 == nil || 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 == nil || 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 == nil || 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 // GetHostTemplate returns the template used to build the
// route match. // route match.
// This is useful for building simple REST API documentation and for instrumentation // This is useful for building simple REST API documentation and for instrumentation
@ -599,11 +715,22 @@ func (r *Route) buildVars(m map[string]string) map[string]string {
// parentRoute allows routes to know about parent host and path definitions. // parentRoute allows routes to know about parent host and path definitions.
type parentRoute interface { type parentRoute interface {
getBuildScheme() string
getNamedRoutes() map[string]*Route getNamedRoutes() map[string]*Route
getRegexpGroup() *routeRegexpGroup getRegexpGroup() *routeRegexpGroup
buildVars(map[string]string) map[string]string buildVars(map[string]string) map[string]string
} }
func (r *Route) getBuildScheme() string {
if r.buildScheme != "" {
return r.buildScheme
}
if r.parent != nil {
return r.parent.getBuildScheme()
}
return ""
}
// getNamedRoutes returns the map where named routes are registered. // getNamedRoutes returns the map where named routes are registered.
func (r *Route) getNamedRoutes() map[string]*Route { func (r *Route) getNamedRoutes() map[string]*Route {
if r.parent == nil { if r.parent == nil {

19
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)
}

10
vendor/modules.txt vendored
View file

@ -1,7 +1,7 @@
# git.giftfish.de/ston1th/godrop v0.0.0-20170420131745-108583814ef5 # git.giftfish.de/ston1th/godrop/v2 v2.0.1
git.giftfish.de/ston1th/godrop git.giftfish.de/ston1th/godrop/v2
# git.giftfish.de/ston1th/jwt v0.0.0-20180913142945-4076e5cf1740 # git.giftfish.de/ston1th/jwt/v3 v3.0.0
git.giftfish.de/ston1th/jwt git.giftfish.de/ston1th/jwt/v3
# github.com/RoaringBitmap/roaring v0.4.16 # github.com/RoaringBitmap/roaring v0.4.16
github.com/RoaringBitmap/roaring github.com/RoaringBitmap/roaring
# github.com/Smerity/govarint v0.0.0-20150407073650-7265e41f48f1 # github.com/Smerity/govarint v0.0.0-20150407073650-7265e41f48f1
@ -65,7 +65,7 @@ github.com/golang/protobuf/proto
github.com/golang/snappy github.com/golang/snappy
# github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f # github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f
github.com/gorilla/context github.com/gorilla/context
# github.com/gorilla/mux v1.3.0 # github.com/gorilla/mux v1.6.2
github.com/gorilla/mux github.com/gorilla/mux
# github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae # github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae
github.com/mschoch/smat github.com/mschoch/smat