Replaced net/http with julienschmidt/httprouter and removed (broken) video support, changed stats/debug endpoints
This commit is contained in:
parent
29afaa3025
commit
abae8ba4c1
|
@ -1,14 +1,14 @@
|
|||
## About
|
||||
|
||||
Sometimes, you just need a way to randomly display media from your filesystem.
|
||||
Sometimes, you just need a way to randomly display images from your filesystem.
|
||||
|
||||
Simply point this tool at one or more directories, and then open the specified port (default `8080`) in your browser.
|
||||
|
||||
A new file will be selected if you open `/` directly, or if you click on any displayed media.
|
||||
A new file will be selected if you open `/` directly, or if you click on any displayed images.
|
||||
|
||||
Browser history is preserved, so you can always go back to any previously displayed media.
|
||||
Browser history is preserved, so you can always go back to any previously displayed images.
|
||||
|
||||
Supported file types and extensions are `bmp`, `gif`, `jp[e]g`, `png`, `webp`, `mp4`, `ogv`, and `webm`.
|
||||
Supported file types and extensions are `bmp`, `gif`, `jp[e]g`, `png`, and `webp`.
|
||||
|
||||
Feature requests, code criticism, bug reports, general chit-chat, and unrelated angst accepted at `roulette@seedno.de`.
|
||||
|
||||
|
|
26
cmd/files.go
26
cmd/files.go
|
@ -159,6 +159,8 @@ func imageDimensions(path string) (*Dimensions, error) {
|
|||
}
|
||||
|
||||
func preparePath(path string) string {
|
||||
path = ImagePrefix + path
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
path = fmt.Sprintf("/%s", filepath.ToSlash(path))
|
||||
}
|
||||
|
@ -168,12 +170,12 @@ func preparePath(path string) string {
|
|||
|
||||
func appendPath(directory, path string, files *Files, stats *ScanStats, shouldCache bool) error {
|
||||
if shouldCache {
|
||||
image, video, err := isSupportedFileType(path)
|
||||
image, err := isSupportedFileType(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !(image || video) {
|
||||
if !image {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
@ -382,13 +384,13 @@ func pathIsValid(filePath string, paths []string) bool {
|
|||
}
|
||||
}
|
||||
|
||||
func isSupportedFileType(path string) (bool, bool, error) {
|
||||
func isSupportedFileType(path string) (bool, error) {
|
||||
file, err := os.Open(path)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
return false, false, nil
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, false, err
|
||||
return false, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
|
@ -397,11 +399,9 @@ func isSupportedFileType(path string) (bool, bool, error) {
|
|||
|
||||
switch {
|
||||
case filetype.IsImage(head):
|
||||
return true, false, nil
|
||||
case filetype.IsVideo(head):
|
||||
return false, true, nil
|
||||
return true, nil
|
||||
default:
|
||||
return false, false, nil
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -417,12 +417,12 @@ func pathHasSupportedFiles(path string) (bool, error) {
|
|||
case !recursive && info.IsDir() && p != path:
|
||||
return filepath.SkipDir
|
||||
case !info.IsDir():
|
||||
image, video, err := isSupportedFileType(p)
|
||||
image, err := isSupportedFileType(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if image || video {
|
||||
if image {
|
||||
hasSupportedFiles <- true
|
||||
return filepath.SkipAll
|
||||
}
|
||||
|
@ -616,12 +616,12 @@ func pickFile(args []string, filters *Filters, sort string, index *Index) (strin
|
|||
filePath := fileList[r]
|
||||
|
||||
if !fromCache {
|
||||
image, video, err := isSupportedFileType(filePath)
|
||||
image, err := isSupportedFileType(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if image || video {
|
||||
if image {
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
|
|
|
@ -74,5 +74,5 @@ func init() {
|
|||
})
|
||||
|
||||
rootCmd.SetVersionTemplate("roulette v{{.Version}}\n")
|
||||
rootCmd.Version = "0.49.2"
|
||||
rootCmd.Version = "0.50.0"
|
||||
}
|
||||
|
|
127
cmd/web.go
127
cmd/web.go
|
@ -29,6 +29,7 @@ import (
|
|||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"github.com/yosssi/gohtml"
|
||||
)
|
||||
|
@ -38,7 +39,8 @@ var favicons embed.FS
|
|||
|
||||
const (
|
||||
LogDate string = `2006-01-02T15:04:05.000-07:00`
|
||||
Prefix string = `/src`
|
||||
SourcePrefix string = `/source`
|
||||
ImagePrefix string = `/view`
|
||||
RedirectStatusCode int = http.StatusSeeOther
|
||||
Timeout time.Duration = 10 * time.Second
|
||||
)
|
||||
|
@ -426,6 +428,31 @@ func notFound(w http.ResponseWriter, r *http.Request, filePath string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func serverError() func(http.ResponseWriter, *http.Request, interface{}) {
|
||||
return func(w http.ResponseWriter, r *http.Request, i interface{}) {
|
||||
startTime := time.Now()
|
||||
|
||||
if verbose {
|
||||
fmt.Printf("%s | Invalid request for %s from %s\n",
|
||||
startTime.Format(LogDate),
|
||||
r.URL.Path,
|
||||
r.RemoteAddr,
|
||||
)
|
||||
}
|
||||
|
||||
w.WriteHeader(500)
|
||||
w.Header().Add("Content-Type", "text/html")
|
||||
|
||||
var htmlBody strings.Builder
|
||||
htmlBody.WriteString(`<!DOCTYPE html><html lang="en"><head>`)
|
||||
htmlBody.WriteString(`<style>a{display:block;height:100%;width:100%;text-decoration:none;color:inherit;cursor:auto;}</style>`)
|
||||
htmlBody.WriteString(`<title>Server Error</title></head>`)
|
||||
htmlBody.WriteString(`<body><a href="/">500 Internal Server Error</a></body></html>`)
|
||||
|
||||
io.WriteString(w, gohtml.Format(htmlBody.String()))
|
||||
}
|
||||
}
|
||||
|
||||
func RefreshInterval(r *http.Request, Regexes *Regexes) (int64, string) {
|
||||
refreshInterval := r.URL.Query().Get("refresh")
|
||||
|
||||
|
@ -530,7 +557,7 @@ func stripQueryParams(u string) (string, error) {
|
|||
func generateFilePath(filePath string) string {
|
||||
var htmlBody strings.Builder
|
||||
|
||||
htmlBody.WriteString(Prefix)
|
||||
htmlBody.WriteString(SourcePrefix)
|
||||
if runtime.GOOS == "windows" {
|
||||
htmlBody.WriteString(`/`)
|
||||
}
|
||||
|
@ -571,8 +598,8 @@ func realIP(r *http.Request) string {
|
|||
}
|
||||
}
|
||||
|
||||
func serveCacheClear(args []string, index *Index) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
func serveCacheClear(args []string, index *Index) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
index.generateCache(args)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
@ -581,8 +608,8 @@ func serveCacheClear(args []string, index *Index) http.HandlerFunc {
|
|||
}
|
||||
}
|
||||
|
||||
func serveStats(args []string, stats *ServeStats) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
func serveStats(args []string, stats *ServeStats) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
|
@ -622,8 +649,8 @@ func serveStats(args []string, stats *ServeStats) http.HandlerFunc {
|
|||
}
|
||||
}
|
||||
|
||||
func serveDebugHtml(args []string, index *Index) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
func serveDebugHtml(args []string, index *Index) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
|
||||
|
@ -670,8 +697,8 @@ func serveDebugHtml(args []string, index *Index) http.HandlerFunc {
|
|||
}
|
||||
}
|
||||
|
||||
func serveDebugJson(args []string, index *Index) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
func serveDebugJson(args []string, index *Index) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
|
@ -701,15 +728,17 @@ func serveDebugJson(args []string, index *Index) http.HandlerFunc {
|
|||
}
|
||||
}
|
||||
|
||||
func serveStaticFile(paths []string, stats *ServeStats) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
prefixedFilePath, err := stripQueryParams(r.URL.Path)
|
||||
func serveStaticFile(paths []string, stats *ServeStats) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
path := strings.TrimPrefix(r.URL.Path, SourcePrefix)
|
||||
|
||||
prefixedFilePath, err := stripQueryParams(path)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
filePath, err := filepath.EvalSymlinks(strings.TrimPrefix(prefixedFilePath, Prefix))
|
||||
filePath, err := filepath.EvalSymlinks(strings.TrimPrefix(prefixedFilePath, SourcePrefix))
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
|
@ -761,8 +790,8 @@ func serveStaticFile(paths []string, stats *ServeStats) http.HandlerFunc {
|
|||
}
|
||||
}
|
||||
|
||||
func serveMedia(paths []string, Regexes *Regexes, index *Index) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
func serveRoot(paths []string, Regexes *Regexes, index *Index) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
refererUri, err := stripQueryParams(refererToUri(r.Referer()))
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
|
@ -778,9 +807,7 @@ func serveMedia(paths []string, Regexes *Regexes, index *Index) http.HandlerFunc
|
|||
|
||||
_, refreshInterval := RefreshInterval(r, Regexes)
|
||||
|
||||
if r.URL.Path == "/" {
|
||||
var filePath string
|
||||
var err error
|
||||
|
||||
if refererUri != "" {
|
||||
filePath, err = nextFile(refererUri, sortOrder, Regexes)
|
||||
|
@ -822,8 +849,19 @@ func serveMedia(paths []string, Regexes *Regexes, index *Index) http.HandlerFunc
|
|||
queryParams,
|
||||
)
|
||||
http.Redirect(w, r, newUrl, RedirectStatusCode)
|
||||
} else {
|
||||
filePath := r.URL.Path
|
||||
}
|
||||
}
|
||||
|
||||
func serveImage(paths []string, Regexes *Regexes, index *Index) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
filters := &Filters{
|
||||
includes: splitQueryParams(r.URL.Query().Get("include"), Regexes),
|
||||
excludes: splitQueryParams(r.URL.Query().Get("exclude"), Regexes),
|
||||
}
|
||||
|
||||
sortOrder := SortOrder(r)
|
||||
|
||||
filePath := strings.TrimPrefix(r.URL.Path, ImagePrefix)
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
filePath = strings.TrimPrefix(filePath, "/")
|
||||
|
@ -840,13 +878,13 @@ func serveMedia(paths []string, Regexes *Regexes, index *Index) http.HandlerFunc
|
|||
return
|
||||
}
|
||||
|
||||
image, video, err := isSupportedFileType(filePath)
|
||||
image, err := isSupportedFileType(filePath)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
if !(image || video) {
|
||||
if !image {
|
||||
notFound(w, r, filePath)
|
||||
|
||||
return
|
||||
|
@ -866,8 +904,6 @@ func serveMedia(paths []string, Regexes *Regexes, index *Index) http.HandlerFunc
|
|||
|
||||
w.Header().Add("Content-Type", "text/html")
|
||||
|
||||
sortOrder := SortOrder(r)
|
||||
|
||||
refreshTimer, refreshInterval := RefreshInterval(r, Regexes)
|
||||
|
||||
queryParams := generateQueryParams(filters, sortOrder, refreshInterval)
|
||||
|
@ -883,38 +919,24 @@ func serveMedia(paths []string, Regexes *Regexes, index *Index) http.HandlerFunc
|
|||
htmlBody.WriteString(`<meta name="theme-color" content="#ffffff">`)
|
||||
htmlBody.WriteString(`<style>html,body{margin:0;padding:0;height:100%;}`)
|
||||
htmlBody.WriteString(`a{display:block;height:100%;width:100%;text-decoration:none;}`)
|
||||
htmlBody.WriteString(`img,video{margin:auto;display:block;max-width:97%;max-height:97%;object-fit:scale-down;`)
|
||||
htmlBody.WriteString(`img{margin:auto;display:block;max-width:97%;max-height:97%;object-fit:scale-down;`)
|
||||
htmlBody.WriteString(`position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);}</style>`)
|
||||
switch {
|
||||
case image:
|
||||
htmlBody.WriteString(fmt.Sprintf(`<title>%s (%dx%d)</title>`,
|
||||
fileName,
|
||||
dimensions.width,
|
||||
dimensions.height))
|
||||
case video:
|
||||
htmlBody.WriteString(fmt.Sprintf(`<title>%s</title>`,
|
||||
fileName))
|
||||
}
|
||||
htmlBody.WriteString(`</head><body>`)
|
||||
if refreshInterval != "0ms" {
|
||||
htmlBody.WriteString(fmt.Sprintf("<script>window.onload = function(){setInterval(function(){window.location.href = '/%s';}, %d);};</script>",
|
||||
queryParams,
|
||||
refreshTimer))
|
||||
}
|
||||
switch {
|
||||
case image:
|
||||
htmlBody.WriteString(fmt.Sprintf(`<a href="/%s"><img src="%s" width="%d" height="%d" alt="Roulette selected: %s"></a>`,
|
||||
queryParams,
|
||||
generateFilePath(filePath),
|
||||
dimensions.width,
|
||||
dimensions.height,
|
||||
fileName))
|
||||
case video:
|
||||
htmlBody.WriteString(fmt.Sprintf(`<a href="/%s"><video src="%s" alt="Roulette selected: %s" autoplay controls></a>`,
|
||||
queryParams,
|
||||
generateFilePath(filePath),
|
||||
fileName))
|
||||
}
|
||||
htmlBody.WriteString(`</body></html>`)
|
||||
|
||||
_, err = io.WriteString(w, gohtml.Format(htmlBody.String()))
|
||||
|
@ -923,10 +945,10 @@ func serveMedia(paths []string, Regexes *Regexes, index *Index) http.HandlerFunc
|
|||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func serveFavicons() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func serveFavicons() httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
fname := strings.TrimPrefix(r.URL.Path, "/")
|
||||
|
||||
data, err := favicons.ReadFile(fname)
|
||||
|
@ -972,7 +994,9 @@ func ServePage(args []string) error {
|
|||
list: []string{},
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux := httprouter.New()
|
||||
|
||||
mux.PanicHandler = serverError()
|
||||
|
||||
if cache {
|
||||
skipIndex := false
|
||||
|
@ -988,7 +1012,7 @@ func ServePage(args []string) error {
|
|||
index.generateCache(args)
|
||||
}
|
||||
|
||||
mux.Handle("/_/clear_cache", serveCacheClear(args, index))
|
||||
mux.GET("/clear_cache", serveCacheClear(args, index))
|
||||
}
|
||||
|
||||
stats := &ServeStats{
|
||||
|
@ -1013,19 +1037,22 @@ func ServePage(args []string) error {
|
|||
}
|
||||
|
||||
if statistics {
|
||||
mux.Handle("/_/stats", serveStats(args, stats))
|
||||
mux.GET("/stats", serveStats(args, stats))
|
||||
}
|
||||
|
||||
if debug {
|
||||
mux.Handle("/_/html", serveDebugHtml(args, index))
|
||||
mux.Handle("/_/json", serveDebugJson(args, index))
|
||||
mux.GET("/html", serveDebugHtml(args, index))
|
||||
|
||||
mux.GET("/json", serveDebugJson(args, index))
|
||||
}
|
||||
|
||||
mux.Handle("/favicons/", serveFavicons())
|
||||
mux.GET("/favicons/*favicon", serveFavicons())
|
||||
|
||||
mux.Handle(Prefix+"/", http.StripPrefix(Prefix, serveStaticFile(paths, stats)))
|
||||
mux.GET(SourcePrefix+"/*static", serveStaticFile(paths, stats))
|
||||
|
||||
mux.Handle("/", serveMedia(paths, Regexes, index))
|
||||
mux.GET("/", serveRoot(paths, Regexes, index))
|
||||
|
||||
mux.GET(ImagePrefix+"/*image", serveImage(paths, Regexes, index))
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: net.JoinHostPort(bind, strconv.FormatInt(int64(port), 10)),
|
||||
|
|
1
go.mod
1
go.mod
|
@ -4,6 +4,7 @@ go 1.20
|
|||
|
||||
require (
|
||||
github.com/h2non/filetype v1.1.3
|
||||
github.com/julienschmidt/httprouter v1.3.0
|
||||
github.com/klauspost/compress v1.16.5
|
||||
github.com/spf13/cobra v1.7.0
|
||||
github.com/yosssi/gohtml v0.0.0-20201013000340-ee4748c638f4
|
||||
|
|
2
go.sum
2
go.sum
|
@ -3,6 +3,8 @@ github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg=
|
|||
github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.16.5 h1:IFV2oUNUzZaz+XyusxpLzpzS8Pt5rh0Z16For/djlyI=
|
||||
github.com/klauspost/compress v1.16.5/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- 1.10.x
|
||||
- 1.11.x
|
||||
- 1.12.x
|
||||
- 1.13.x
|
||||
- master
|
||||
before_install:
|
||||
- go get github.com/mattn/goveralls
|
||||
script:
|
||||
- go test -v -covermode=count -coverprofile=coverage.out
|
||||
- go vet ./...
|
||||
- test -z "$(gofmt -d -s . | tee /dev/stderr)"
|
||||
- $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci
|
|
@ -0,0 +1,29 @@
|
|||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2013, Julien Schmidt
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -0,0 +1,300 @@
|
|||
# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.svg?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![Coverage Status](https://coveralls.io/repos/github/julienschmidt/httprouter/badge.svg?branch=master)](https://coveralls.io/github/julienschmidt/httprouter?branch=master) [![GoDoc](https://godoc.org/github.com/julienschmidt/httprouter?status.svg)](http://godoc.org/github.com/julienschmidt/httprouter)
|
||||
|
||||
HttpRouter is a lightweight high performance HTTP request router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/).
|
||||
|
||||
In contrast to the [default mux](https://golang.org/pkg/net/http/#ServeMux) of Go's `net/http` package, this router supports variables in the routing pattern and matches against the request method. It also scales better.
|
||||
|
||||
The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching.
|
||||
|
||||
## Features
|
||||
|
||||
**Only explicit matches:** With other routers, like [`http.ServeMux`](https://golang.org/pkg/net/http/#ServeMux), a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like *longest match* or *first registered, first matched*. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.
|
||||
|
||||
**Stop caring about trailing slashes:** Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can [turn off this behavior](https://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash).
|
||||
|
||||
**Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL.
|
||||
|
||||
**Parameters in your routing pattern:** Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.
|
||||
|
||||
**Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard `Handler`/`HandlerFunc` API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary.
|
||||
|
||||
**Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark). See below for technical details of the implementation.
|
||||
|
||||
**No more server crashes:** You can set a [Panic handler](https://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics occurring during handling a HTTP request. The router then recovers and lets the `PanicHandler` log what happened and deliver a nice error page.
|
||||
|
||||
**Perfect for APIs:** The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) and `405 Method Not Allowed` replies.
|
||||
|
||||
Of course you can also set **custom [`NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](https://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles).
|
||||
|
||||
## Usage
|
||||
|
||||
This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details.
|
||||
|
||||
Let's start with a trivial example:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"log"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "Welcome!\n")
|
||||
}
|
||||
|
||||
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
|
||||
}
|
||||
|
||||
func main() {
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/hello/:name", Hello)
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", router))
|
||||
}
|
||||
```
|
||||
|
||||
### Named parameters
|
||||
|
||||
As you can see, `:name` is a *named parameter*. The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s. You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method: `:name` can be retrieved by `ByName("name")`.
|
||||
|
||||
When using a `http.Handler` (using `router.Handler` or `http.HandlerFunc`) instead of HttpRouter's handle API using a 3rd function parameter, the named parameters are stored in the `request.Context`. See more below under [Why doesn't this work with http.Handler?](#why-doesnt-this-work-with-httphandler).
|
||||
|
||||
Named parameters only match a single path segment:
|
||||
|
||||
```
|
||||
Pattern: /user/:user
|
||||
|
||||
/user/gordon match
|
||||
/user/you match
|
||||
/user/gordon/profile no match
|
||||
/user/ no match
|
||||
```
|
||||
|
||||
**Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other.
|
||||
|
||||
### Catch-All parameters
|
||||
|
||||
The second type are *catch-all* parameters and have the form `*name`. Like the name suggests, they match everything. Therefore they must always be at the **end** of the pattern:
|
||||
|
||||
```
|
||||
Pattern: /src/*filepath
|
||||
|
||||
/src/ match
|
||||
/src/somefile.go match
|
||||
/src/subdir/somefile.go match
|
||||
```
|
||||
|
||||
## How does it work?
|
||||
|
||||
The router relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://en.wikipedia.org/wiki/Radix_tree)). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the `GET` request method could look like:
|
||||
|
||||
```
|
||||
Priority Path Handle
|
||||
9 \ *<1>
|
||||
3 ├s nil
|
||||
2 |├earch\ *<2>
|
||||
1 |└upport\ *<3>
|
||||
2 ├blog\ *<4>
|
||||
1 | └:post nil
|
||||
1 | └\ *<5>
|
||||
2 ├about-us\ *<6>
|
||||
1 | └team\ *<7>
|
||||
1 └contact\ *<8>
|
||||
```
|
||||
|
||||
Every `*<num>` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark), this works very well and efficient.
|
||||
|
||||
Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree.
|
||||
|
||||
For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways:
|
||||
|
||||
1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible.
|
||||
2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right.
|
||||
|
||||
```
|
||||
├------------
|
||||
├---------
|
||||
├-----
|
||||
├----
|
||||
├--
|
||||
├--
|
||||
└-
|
||||
```
|
||||
|
||||
## Why doesn't this work with `http.Handler`?
|
||||
|
||||
**It does!** The router itself implements the `http.Handler` interface. Moreover the router provides convenient [adapters for `http.Handler`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [`http.HandlerFunc`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s which allows them to be used as a [`httprouter.Handle`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route.
|
||||
|
||||
Named parameters can be accessed `request.Context`:
|
||||
|
||||
```go
|
||||
func Hello(w http.ResponseWriter, r *http.Request) {
|
||||
params := httprouter.ParamsFromContext(r.Context())
|
||||
|
||||
fmt.Fprintf(w, "hello, %s!\n", params.ByName("name"))
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, one can also use `params := r.Context().Value(httprouter.ParamsKey)` instead of the helper function.
|
||||
|
||||
Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.
|
||||
|
||||
## Automatic OPTIONS responses and CORS
|
||||
|
||||
One might wish to modify automatic responses to OPTIONS requests, e.g. to support [CORS preflight requests](https://developer.mozilla.org/en-US/docs/Glossary/preflight_request) or to set other headers.
|
||||
This can be achieved using the [`Router.GlobalOPTIONS`](https://godoc.org/github.com/julienschmidt/httprouter#Router.GlobalOPTIONS) handler:
|
||||
|
||||
```go
|
||||
router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Access-Control-Request-Method") != "" {
|
||||
// Set CORS headers
|
||||
header := w.Header()
|
||||
header.Set("Access-Control-Allow-Methods", r.Header.Get("Allow"))
|
||||
header.Set("Access-Control-Allow-Origin", "*")
|
||||
}
|
||||
|
||||
// Adjust status code to 204
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
```
|
||||
|
||||
## Where can I find Middleware *X*?
|
||||
|
||||
This package just provides a very efficient request router with a few extra features. The router is just a [`http.Handler`](https://golang.org/pkg/net/http/#Handler), you can chain any http.Handler compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](https://justinas.org/writing-http-middleware-in-go/), it's very easy!
|
||||
|
||||
Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter).
|
||||
|
||||
### Multi-domain / Sub-domains
|
||||
|
||||
Here is a quick example: Does your server serve multiple domains / hosts?
|
||||
You want to use sub-domains?
|
||||
Define a router per host!
|
||||
|
||||
```go
|
||||
// We need an object that implements the http.Handler interface.
|
||||
// Therefore we need a type for which we implement the ServeHTTP method.
|
||||
// We just use a map here, in which we map host names (with port) to http.Handlers
|
||||
type HostSwitch map[string]http.Handler
|
||||
|
||||
// Implement the ServeHTTP method on our new type
|
||||
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Check if a http.Handler is registered for the given host.
|
||||
// If yes, use it to handle the request.
|
||||
if handler := hs[r.Host]; handler != nil {
|
||||
handler.ServeHTTP(w, r)
|
||||
} else {
|
||||
// Handle host names for which no handler is registered
|
||||
http.Error(w, "Forbidden", 403) // Or Redirect?
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Initialize a router as usual
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/hello/:name", Hello)
|
||||
|
||||
// Make a new HostSwitch and insert the router (our http handler)
|
||||
// for example.com and port 12345
|
||||
hs := make(HostSwitch)
|
||||
hs["example.com:12345"] = router
|
||||
|
||||
// Use the HostSwitch to listen and serve on port 12345
|
||||
log.Fatal(http.ListenAndServe(":12345", hs))
|
||||
}
|
||||
```
|
||||
|
||||
### Basic Authentication
|
||||
|
||||
Another quick example: Basic Authentication (RFC 2617) for handles:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
// Get the Basic Authentication credentials
|
||||
user, password, hasAuth := r.BasicAuth()
|
||||
|
||||
if hasAuth && user == requiredUser && password == requiredPassword {
|
||||
// Delegate request to the given handle
|
||||
h(w, r, ps)
|
||||
} else {
|
||||
// Request Basic Authentication otherwise
|
||||
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
|
||||
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "Not protected!\n")
|
||||
}
|
||||
|
||||
func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "Protected!\n")
|
||||
}
|
||||
|
||||
func main() {
|
||||
user := "gordon"
|
||||
pass := "secret!"
|
||||
|
||||
router := httprouter.New()
|
||||
router.GET("/", Index)
|
||||
router.GET("/protected/", BasicAuth(Protected, user, pass))
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", router))
|
||||
}
|
||||
```
|
||||
|
||||
## Chaining with the NotFound handler
|
||||
|
||||
**NOTE: It might be required to set [`Router.HandleMethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.**
|
||||
|
||||
You can use another [`http.Handler`](https://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [`Router.NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining.
|
||||
|
||||
### Static files
|
||||
|
||||
The `NotFound` handler can for example be used to serve static files from the root path `/` (like an `index.html` file along with other assets):
|
||||
|
||||
```go
|
||||
// Serve static files from the ./public directory
|
||||
router.NotFound = http.FileServer(http.Dir("public"))
|
||||
```
|
||||
|
||||
But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`.
|
||||
|
||||
## Web Frameworks based on HttpRouter
|
||||
|
||||
If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:
|
||||
|
||||
* [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework
|
||||
* [api2go](https://github.com/manyminds/api2go): A JSON API Implementation for Go
|
||||
* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance
|
||||
* [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go
|
||||
* [goMiddlewareChain](https://github.com/TobiEiss/goMiddlewareChain): An express.js-like-middleware-chain
|
||||
* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine
|
||||
* [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow
|
||||
* [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support
|
||||
* [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context
|
||||
* [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba
|
||||
* [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang
|
||||
* [pbgo](https://github.com/chai2010/pbgo): pbgo is a mini RPC/REST framework based on Protobuf
|
||||
* [River](https://github.com/abiosoft/river): River is a simple and lightweight REST server
|
||||
* [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts
|
||||
* [xmux](https://github.com/rs/xmux): xmux is a httprouter fork on top of xhandler (net/context aware)
|
|
@ -0,0 +1,123 @@
|
|||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
||||
// Based on the path package, Copyright 2009 The Go Authors.
|
||||
// Use of this source code is governed by a BSD-style license that can be found
|
||||
// in the LICENSE file.
|
||||
|
||||
package httprouter
|
||||
|
||||
// CleanPath is the URL version of path.Clean, it returns a canonical URL path
|
||||
// for p, eliminating . and .. elements.
|
||||
//
|
||||
// The following rules are applied iteratively until no further processing can
|
||||
// be done:
|
||||
// 1. Replace multiple slashes with a single slash.
|
||||
// 2. Eliminate each . path name element (the current directory).
|
||||
// 3. Eliminate each inner .. path name element (the parent directory)
|
||||
// along with the non-.. element that precedes it.
|
||||
// 4. Eliminate .. elements that begin a rooted path:
|
||||
// that is, replace "/.." by "/" at the beginning of a path.
|
||||
//
|
||||
// If the result of this process is an empty string, "/" is returned
|
||||
func CleanPath(p string) string {
|
||||
// Turn empty string into "/"
|
||||
if p == "" {
|
||||
return "/"
|
||||
}
|
||||
|
||||
n := len(p)
|
||||
var buf []byte
|
||||
|
||||
// Invariants:
|
||||
// reading from path; r is index of next byte to process.
|
||||
// writing to buf; w is index of next byte to write.
|
||||
|
||||
// path must start with '/'
|
||||
r := 1
|
||||
w := 1
|
||||
|
||||
if p[0] != '/' {
|
||||
r = 0
|
||||
buf = make([]byte, n+1)
|
||||
buf[0] = '/'
|
||||
}
|
||||
|
||||
trailing := n > 1 && p[n-1] == '/'
|
||||
|
||||
// A bit more clunky without a 'lazybuf' like the path package, but the loop
|
||||
// gets completely inlined (bufApp). So in contrast to the path package this
|
||||
// loop has no expensive function calls (except 1x make)
|
||||
|
||||
for r < n {
|
||||
switch {
|
||||
case p[r] == '/':
|
||||
// empty path element, trailing slash is added after the end
|
||||
r++
|
||||
|
||||
case p[r] == '.' && r+1 == n:
|
||||
trailing = true
|
||||
r++
|
||||
|
||||
case p[r] == '.' && p[r+1] == '/':
|
||||
// . element
|
||||
r += 2
|
||||
|
||||
case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
|
||||
// .. element: remove to last /
|
||||
r += 3
|
||||
|
||||
if w > 1 {
|
||||
// can backtrack
|
||||
w--
|
||||
|
||||
if buf == nil {
|
||||
for w > 1 && p[w] != '/' {
|
||||
w--
|
||||
}
|
||||
} else {
|
||||
for w > 1 && buf[w] != '/' {
|
||||
w--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
// real path element.
|
||||
// add slash if needed
|
||||
if w > 1 {
|
||||
bufApp(&buf, p, w, '/')
|
||||
w++
|
||||
}
|
||||
|
||||
// copy element
|
||||
for r < n && p[r] != '/' {
|
||||
bufApp(&buf, p, w, p[r])
|
||||
w++
|
||||
r++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// re-append trailing slash
|
||||
if trailing && w > 1 {
|
||||
bufApp(&buf, p, w, '/')
|
||||
w++
|
||||
}
|
||||
|
||||
if buf == nil {
|
||||
return p[:w]
|
||||
}
|
||||
return string(buf[:w])
|
||||
}
|
||||
|
||||
// internal helper to lazily create a buffer if necessary
|
||||
func bufApp(buf *[]byte, s string, w int, c byte) {
|
||||
if *buf == nil {
|
||||
if s[w] == c {
|
||||
return
|
||||
}
|
||||
|
||||
*buf = make([]byte, len(s))
|
||||
copy(*buf, s[:w])
|
||||
}
|
||||
(*buf)[w] = c
|
||||
}
|
|
@ -0,0 +1,452 @@
|
|||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be found
|
||||
// in the LICENSE file.
|
||||
|
||||
// Package httprouter is a trie based high performance HTTP request router.
|
||||
//
|
||||
// A trivial example is:
|
||||
//
|
||||
// package main
|
||||
//
|
||||
// import (
|
||||
// "fmt"
|
||||
// "github.com/julienschmidt/httprouter"
|
||||
// "net/http"
|
||||
// "log"
|
||||
// )
|
||||
//
|
||||
// func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
// fmt.Fprint(w, "Welcome!\n")
|
||||
// }
|
||||
//
|
||||
// func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
// fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
|
||||
// }
|
||||
//
|
||||
// func main() {
|
||||
// router := httprouter.New()
|
||||
// router.GET("/", Index)
|
||||
// router.GET("/hello/:name", Hello)
|
||||
//
|
||||
// log.Fatal(http.ListenAndServe(":8080", router))
|
||||
// }
|
||||
//
|
||||
// The router matches incoming requests by the request method and the path.
|
||||
// If a handle is registered for this path and method, the router delegates the
|
||||
// request to that function.
|
||||
// For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
|
||||
// register handles, for all other methods router.Handle can be used.
|
||||
//
|
||||
// The registered path, against which the router matches incoming requests, can
|
||||
// contain two types of parameters:
|
||||
// Syntax Type
|
||||
// :name named parameter
|
||||
// *name catch-all parameter
|
||||
//
|
||||
// Named parameters are dynamic path segments. They match anything until the
|
||||
// next '/' or the path end:
|
||||
// Path: /blog/:category/:post
|
||||
//
|
||||
// Requests:
|
||||
// /blog/go/request-routers match: category="go", post="request-routers"
|
||||
// /blog/go/request-routers/ no match, but the router would redirect
|
||||
// /blog/go/ no match
|
||||
// /blog/go/request-routers/comments no match
|
||||
//
|
||||
// Catch-all parameters match anything until the path end, including the
|
||||
// directory index (the '/' before the catch-all). Since they match anything
|
||||
// until the end, catch-all parameters must always be the final path element.
|
||||
// Path: /files/*filepath
|
||||
//
|
||||
// Requests:
|
||||
// /files/ match: filepath="/"
|
||||
// /files/LICENSE match: filepath="/LICENSE"
|
||||
// /files/templates/article.html match: filepath="/templates/article.html"
|
||||
// /files no match, but the router would redirect
|
||||
//
|
||||
// The value of parameters is saved as a slice of the Param struct, consisting
|
||||
// each of a key and a value. The slice is passed to the Handle func as a third
|
||||
// parameter.
|
||||
// There are two ways to retrieve the value of a parameter:
|
||||
// // by the name of the parameter
|
||||
// user := ps.ByName("user") // defined by :user or *user
|
||||
//
|
||||
// // by the index of the parameter. This way you can also get the name (key)
|
||||
// thirdKey := ps[2].Key // the name of the 3rd parameter
|
||||
// thirdValue := ps[2].Value // the value of the 3rd parameter
|
||||
package httprouter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Handle is a function that can be registered to a route to handle HTTP
|
||||
// requests. Like http.HandlerFunc, but has a third parameter for the values of
|
||||
// wildcards (variables).
|
||||
type Handle func(http.ResponseWriter, *http.Request, Params)
|
||||
|
||||
// Param is a single URL parameter, consisting of a key and a value.
|
||||
type Param struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
// Params is a Param-slice, as returned by the router.
|
||||
// The slice is ordered, the first URL parameter is also the first slice value.
|
||||
// It is therefore safe to read values by the index.
|
||||
type Params []Param
|
||||
|
||||
// ByName returns the value of the first Param which key matches the given name.
|
||||
// If no matching Param is found, an empty string is returned.
|
||||
func (ps Params) ByName(name string) string {
|
||||
for i := range ps {
|
||||
if ps[i].Key == name {
|
||||
return ps[i].Value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type paramsKey struct{}
|
||||
|
||||
// ParamsKey is the request context key under which URL params are stored.
|
||||
var ParamsKey = paramsKey{}
|
||||
|
||||
// ParamsFromContext pulls the URL parameters from a request context,
|
||||
// or returns nil if none are present.
|
||||
func ParamsFromContext(ctx context.Context) Params {
|
||||
p, _ := ctx.Value(ParamsKey).(Params)
|
||||
return p
|
||||
}
|
||||
|
||||
// Router is a http.Handler which can be used to dispatch requests to different
|
||||
// handler functions via configurable routes
|
||||
type Router struct {
|
||||
trees map[string]*node
|
||||
|
||||
// Enables automatic redirection if the current route can't be matched but a
|
||||
// handler for the path with (without) the trailing slash exists.
|
||||
// For example if /foo/ is requested but a route only exists for /foo, the
|
||||
// client is redirected to /foo with http status code 301 for GET requests
|
||||
// and 307 for all other request methods.
|
||||
RedirectTrailingSlash bool
|
||||
|
||||
// If enabled, the router tries to fix the current request path, if no
|
||||
// handle is registered for it.
|
||||
// First superfluous path elements like ../ or // are removed.
|
||||
// Afterwards the router does a case-insensitive lookup of the cleaned path.
|
||||
// If a handle can be found for this route, the router makes a redirection
|
||||
// to the corrected path with status code 301 for GET requests and 307 for
|
||||
// all other request methods.
|
||||
// For example /FOO and /..//Foo could be redirected to /foo.
|
||||
// RedirectTrailingSlash is independent of this option.
|
||||
RedirectFixedPath bool
|
||||
|
||||
// If enabled, the router checks if another method is allowed for the
|
||||
// current route, if the current request can not be routed.
|
||||
// If this is the case, the request is answered with 'Method Not Allowed'
|
||||
// and HTTP status code 405.
|
||||
// If no other Method is allowed, the request is delegated to the NotFound
|
||||
// handler.
|
||||
HandleMethodNotAllowed bool
|
||||
|
||||
// If enabled, the router automatically replies to OPTIONS requests.
|
||||
// Custom OPTIONS handlers take priority over automatic replies.
|
||||
HandleOPTIONS bool
|
||||
|
||||
// An optional http.Handler that is called on automatic OPTIONS requests.
|
||||
// The handler is only called if HandleOPTIONS is true and no OPTIONS
|
||||
// handler for the specific path was set.
|
||||
// The "Allowed" header is set before calling the handler.
|
||||
GlobalOPTIONS http.Handler
|
||||
|
||||
// Cached value of global (*) allowed methods
|
||||
globalAllowed string
|
||||
|
||||
// Configurable http.Handler which is called when no matching route is
|
||||
// found. If it is not set, http.NotFound is used.
|
||||
NotFound http.Handler
|
||||
|
||||
// Configurable http.Handler which is called when a request
|
||||
// cannot be routed and HandleMethodNotAllowed is true.
|
||||
// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
|
||||
// The "Allow" header with allowed request methods is set before the handler
|
||||
// is called.
|
||||
MethodNotAllowed http.Handler
|
||||
|
||||
// Function to handle panics recovered from http handlers.
|
||||
// It should be used to generate a error page and return the http error code
|
||||
// 500 (Internal Server Error).
|
||||
// The handler can be used to keep your server from crashing because of
|
||||
// unrecovered panics.
|
||||
PanicHandler func(http.ResponseWriter, *http.Request, interface{})
|
||||
}
|
||||
|
||||
// Make sure the Router conforms with the http.Handler interface
|
||||
var _ http.Handler = New()
|
||||
|
||||
// New returns a new initialized Router.
|
||||
// Path auto-correction, including trailing slashes, is enabled by default.
|
||||
func New() *Router {
|
||||
return &Router{
|
||||
RedirectTrailingSlash: true,
|
||||
RedirectFixedPath: true,
|
||||
HandleMethodNotAllowed: true,
|
||||
HandleOPTIONS: true,
|
||||
}
|
||||
}
|
||||
|
||||
// GET is a shortcut for router.Handle(http.MethodGet, path, handle)
|
||||
func (r *Router) GET(path string, handle Handle) {
|
||||
r.Handle(http.MethodGet, path, handle)
|
||||
}
|
||||
|
||||
// HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)
|
||||
func (r *Router) HEAD(path string, handle Handle) {
|
||||
r.Handle(http.MethodHead, path, handle)
|
||||
}
|
||||
|
||||
// OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)
|
||||
func (r *Router) OPTIONS(path string, handle Handle) {
|
||||
r.Handle(http.MethodOptions, path, handle)
|
||||
}
|
||||
|
||||
// POST is a shortcut for router.Handle(http.MethodPost, path, handle)
|
||||
func (r *Router) POST(path string, handle Handle) {
|
||||
r.Handle(http.MethodPost, path, handle)
|
||||
}
|
||||
|
||||
// PUT is a shortcut for router.Handle(http.MethodPut, path, handle)
|
||||
func (r *Router) PUT(path string, handle Handle) {
|
||||
r.Handle(http.MethodPut, path, handle)
|
||||
}
|
||||
|
||||
// PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)
|
||||
func (r *Router) PATCH(path string, handle Handle) {
|
||||
r.Handle(http.MethodPatch, path, handle)
|
||||
}
|
||||
|
||||
// DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)
|
||||
func (r *Router) DELETE(path string, handle Handle) {
|
||||
r.Handle(http.MethodDelete, path, handle)
|
||||
}
|
||||
|
||||
// Handle registers a new request handle with the given path and method.
|
||||
//
|
||||
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
|
||||
// functions can be used.
|
||||
//
|
||||
// This function is intended for bulk loading and to allow the usage of less
|
||||
// frequently used, non-standardized or custom methods (e.g. for internal
|
||||
// communication with a proxy).
|
||||
func (r *Router) Handle(method, path string, handle Handle) {
|
||||
if len(path) < 1 || path[0] != '/' {
|
||||
panic("path must begin with '/' in path '" + path + "'")
|
||||
}
|
||||
|
||||
if r.trees == nil {
|
||||
r.trees = make(map[string]*node)
|
||||
}
|
||||
|
||||
root := r.trees[method]
|
||||
if root == nil {
|
||||
root = new(node)
|
||||
r.trees[method] = root
|
||||
|
||||
r.globalAllowed = r.allowed("*", "")
|
||||
}
|
||||
|
||||
root.addRoute(path, handle)
|
||||
}
|
||||
|
||||
// Handler is an adapter which allows the usage of an http.Handler as a
|
||||
// request handle.
|
||||
// The Params are available in the request context under ParamsKey.
|
||||
func (r *Router) Handler(method, path string, handler http.Handler) {
|
||||
r.Handle(method, path,
|
||||
func(w http.ResponseWriter, req *http.Request, p Params) {
|
||||
if len(p) > 0 {
|
||||
ctx := req.Context()
|
||||
ctx = context.WithValue(ctx, ParamsKey, p)
|
||||
req = req.WithContext(ctx)
|
||||
}
|
||||
handler.ServeHTTP(w, req)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
|
||||
// request handle.
|
||||
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
|
||||
r.Handler(method, path, handler)
|
||||
}
|
||||
|
||||
// ServeFiles serves files from the given file system root.
|
||||
// The path must end with "/*filepath", files are then served from the local
|
||||
// path /defined/root/dir/*filepath.
|
||||
// For example if root is "/etc" and *filepath is "passwd", the local file
|
||||
// "/etc/passwd" would be served.
|
||||
// Internally a http.FileServer is used, therefore http.NotFound is used instead
|
||||
// of the Router's NotFound handler.
|
||||
// To use the operating system's file system implementation,
|
||||
// use http.Dir:
|
||||
// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
|
||||
func (r *Router) ServeFiles(path string, root http.FileSystem) {
|
||||
if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
|
||||
panic("path must end with /*filepath in path '" + path + "'")
|
||||
}
|
||||
|
||||
fileServer := http.FileServer(root)
|
||||
|
||||
r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
|
||||
req.URL.Path = ps.ByName("filepath")
|
||||
fileServer.ServeHTTP(w, req)
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
|
||||
if rcv := recover(); rcv != nil {
|
||||
r.PanicHandler(w, req, rcv)
|
||||
}
|
||||
}
|
||||
|
||||
// Lookup allows the manual lookup of a method + path combo.
|
||||
// This is e.g. useful to build a framework around this router.
|
||||
// If the path was found, it returns the handle function and the path parameter
|
||||
// values. Otherwise the third return value indicates whether a redirection to
|
||||
// the same path with an extra / without the trailing slash should be performed.
|
||||
func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
|
||||
if root := r.trees[method]; root != nil {
|
||||
return root.getValue(path)
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
func (r *Router) allowed(path, reqMethod string) (allow string) {
|
||||
allowed := make([]string, 0, 9)
|
||||
|
||||
if path == "*" { // server-wide
|
||||
// empty method is used for internal calls to refresh the cache
|
||||
if reqMethod == "" {
|
||||
for method := range r.trees {
|
||||
if method == http.MethodOptions {
|
||||
continue
|
||||
}
|
||||
// Add request method to list of allowed methods
|
||||
allowed = append(allowed, method)
|
||||
}
|
||||
} else {
|
||||
return r.globalAllowed
|
||||
}
|
||||
} else { // specific path
|
||||
for method := range r.trees {
|
||||
// Skip the requested method - we already tried this one
|
||||
if method == reqMethod || method == http.MethodOptions {
|
||||
continue
|
||||
}
|
||||
|
||||
handle, _, _ := r.trees[method].getValue(path)
|
||||
if handle != nil {
|
||||
// Add request method to list of allowed methods
|
||||
allowed = append(allowed, method)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(allowed) > 0 {
|
||||
// Add request method to list of allowed methods
|
||||
allowed = append(allowed, http.MethodOptions)
|
||||
|
||||
// Sort allowed methods.
|
||||
// sort.Strings(allowed) unfortunately causes unnecessary allocations
|
||||
// due to allowed being moved to the heap and interface conversion
|
||||
for i, l := 1, len(allowed); i < l; i++ {
|
||||
for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- {
|
||||
allowed[j], allowed[j-1] = allowed[j-1], allowed[j]
|
||||
}
|
||||
}
|
||||
|
||||
// return as comma separated list
|
||||
return strings.Join(allowed, ", ")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ServeHTTP makes the router implement the http.Handler interface.
|
||||
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
if r.PanicHandler != nil {
|
||||
defer r.recv(w, req)
|
||||
}
|
||||
|
||||
path := req.URL.Path
|
||||
|
||||
if root := r.trees[req.Method]; root != nil {
|
||||
if handle, ps, tsr := root.getValue(path); handle != nil {
|
||||
handle(w, req, ps)
|
||||
return
|
||||
} else if req.Method != http.MethodConnect && path != "/" {
|
||||
code := 301 // Permanent redirect, request with GET method
|
||||
if req.Method != http.MethodGet {
|
||||
// Temporary redirect, request with same method
|
||||
// As of Go 1.3, Go does not support status code 308.
|
||||
code = 307
|
||||
}
|
||||
|
||||
if tsr && r.RedirectTrailingSlash {
|
||||
if len(path) > 1 && path[len(path)-1] == '/' {
|
||||
req.URL.Path = path[:len(path)-1]
|
||||
} else {
|
||||
req.URL.Path = path + "/"
|
||||
}
|
||||
http.Redirect(w, req, req.URL.String(), code)
|
||||
return
|
||||
}
|
||||
|
||||
// Try to fix the request path
|
||||
if r.RedirectFixedPath {
|
||||
fixedPath, found := root.findCaseInsensitivePath(
|
||||
CleanPath(path),
|
||||
r.RedirectTrailingSlash,
|
||||
)
|
||||
if found {
|
||||
req.URL.Path = string(fixedPath)
|
||||
http.Redirect(w, req, req.URL.String(), code)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if req.Method == http.MethodOptions && r.HandleOPTIONS {
|
||||
// Handle OPTIONS requests
|
||||
if allow := r.allowed(path, http.MethodOptions); allow != "" {
|
||||
w.Header().Set("Allow", allow)
|
||||
if r.GlobalOPTIONS != nil {
|
||||
r.GlobalOPTIONS.ServeHTTP(w, req)
|
||||
}
|
||||
return
|
||||
}
|
||||
} else if r.HandleMethodNotAllowed { // Handle 405
|
||||
if allow := r.allowed(path, req.Method); allow != "" {
|
||||
w.Header().Set("Allow", allow)
|
||||
if r.MethodNotAllowed != nil {
|
||||
r.MethodNotAllowed.ServeHTTP(w, req)
|
||||
} else {
|
||||
http.Error(w,
|
||||
http.StatusText(http.StatusMethodNotAllowed),
|
||||
http.StatusMethodNotAllowed,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 404
|
||||
if r.NotFound != nil {
|
||||
r.NotFound.ServeHTTP(w, req)
|
||||
} else {
|
||||
http.NotFound(w, req)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,666 @@
|
|||
// Copyright 2013 Julien Schmidt. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be found
|
||||
// in the LICENSE file.
|
||||
|
||||
package httprouter
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func min(a, b int) int {
|
||||
if a <= b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
const maxParamCount uint8 = ^uint8(0)
|
||||
|
||||
func countParams(path string) uint8 {
|
||||
var n uint
|
||||
for i := 0; i < len(path); i++ {
|
||||
if path[i] != ':' && path[i] != '*' {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
}
|
||||
if n >= uint(maxParamCount) {
|
||||
return maxParamCount
|
||||
}
|
||||
|
||||
return uint8(n)
|
||||
}
|
||||
|
||||
type nodeType uint8
|
||||
|
||||
const (
|
||||
static nodeType = iota // default
|
||||
root
|
||||
param
|
||||
catchAll
|
||||
)
|
||||
|
||||
type node struct {
|
||||
path string
|
||||
wildChild bool
|
||||
nType nodeType
|
||||
maxParams uint8
|
||||
priority uint32
|
||||
indices string
|
||||
children []*node
|
||||
handle Handle
|
||||
}
|
||||
|
||||
// increments priority of the given child and reorders if necessary
|
||||
func (n *node) incrementChildPrio(pos int) int {
|
||||
n.children[pos].priority++
|
||||
prio := n.children[pos].priority
|
||||
|
||||
// adjust position (move to front)
|
||||
newPos := pos
|
||||
for newPos > 0 && n.children[newPos-1].priority < prio {
|
||||
// swap node positions
|
||||
n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1]
|
||||
|
||||
newPos--
|
||||
}
|
||||
|
||||
// build new index char string
|
||||
if newPos != pos {
|
||||
n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
|
||||
n.indices[pos:pos+1] + // the index char we move
|
||||
n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
|
||||
}
|
||||
|
||||
return newPos
|
||||
}
|
||||
|
||||
// addRoute adds a node with the given handle to the path.
|
||||
// Not concurrency-safe!
|
||||
func (n *node) addRoute(path string, handle Handle) {
|
||||
fullPath := path
|
||||
n.priority++
|
||||
numParams := countParams(path)
|
||||
|
||||
// non-empty tree
|
||||
if len(n.path) > 0 || len(n.children) > 0 {
|
||||
walk:
|
||||
for {
|
||||
// Update maxParams of the current node
|
||||
if numParams > n.maxParams {
|
||||
n.maxParams = numParams
|
||||
}
|
||||
|
||||
// Find the longest common prefix.
|
||||
// This also implies that the common prefix contains no ':' or '*'
|
||||
// since the existing key can't contain those chars.
|
||||
i := 0
|
||||
max := min(len(path), len(n.path))
|
||||
for i < max && path[i] == n.path[i] {
|
||||
i++
|
||||
}
|
||||
|
||||
// Split edge
|
||||
if i < len(n.path) {
|
||||
child := node{
|
||||
path: n.path[i:],
|
||||
wildChild: n.wildChild,
|
||||
nType: static,
|
||||
indices: n.indices,
|
||||
children: n.children,
|
||||
handle: n.handle,
|
||||
priority: n.priority - 1,
|
||||
}
|
||||
|
||||
// Update maxParams (max of all children)
|
||||
for i := range child.children {
|
||||
if child.children[i].maxParams > child.maxParams {
|
||||
child.maxParams = child.children[i].maxParams
|
||||
}
|
||||
}
|
||||
|
||||
n.children = []*node{&child}
|
||||
// []byte for proper unicode char conversion, see #65
|
||||
n.indices = string([]byte{n.path[i]})
|
||||
n.path = path[:i]
|
||||
n.handle = nil
|
||||
n.wildChild = false
|
||||
}
|
||||
|
||||
// Make new node a child of this node
|
||||
if i < len(path) {
|
||||
path = path[i:]
|
||||
|
||||
if n.wildChild {
|
||||
n = n.children[0]
|
||||
n.priority++
|
||||
|
||||
// Update maxParams of the child node
|
||||
if numParams > n.maxParams {
|
||||
n.maxParams = numParams
|
||||
}
|
||||
numParams--
|
||||
|
||||
// Check if the wildcard matches
|
||||
if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&
|
||||
// Adding a child to a catchAll is not possible
|
||||
n.nType != catchAll &&
|
||||
// Check for longer wildcard, e.g. :name and :names
|
||||
(len(n.path) >= len(path) || path[len(n.path)] == '/') {
|
||||
continue walk
|
||||
} else {
|
||||
// Wildcard conflict
|
||||
var pathSeg string
|
||||
if n.nType == catchAll {
|
||||
pathSeg = path
|
||||
} else {
|
||||
pathSeg = strings.SplitN(path, "/", 2)[0]
|
||||
}
|
||||
prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
|
||||
panic("'" + pathSeg +
|
||||
"' in new path '" + fullPath +
|
||||
"' conflicts with existing wildcard '" + n.path +
|
||||
"' in existing prefix '" + prefix +
|
||||
"'")
|
||||
}
|
||||
}
|
||||
|
||||
c := path[0]
|
||||
|
||||
// slash after param
|
||||
if n.nType == param && c == '/' && len(n.children) == 1 {
|
||||
n = n.children[0]
|
||||
n.priority++
|
||||
continue walk
|
||||
}
|
||||
|
||||
// Check if a child with the next path byte exists
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if c == n.indices[i] {
|
||||
i = n.incrementChildPrio(i)
|
||||
n = n.children[i]
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise insert it
|
||||
if c != ':' && c != '*' {
|
||||
// []byte for proper unicode char conversion, see #65
|
||||
n.indices += string([]byte{c})
|
||||
child := &node{
|
||||
maxParams: numParams,
|
||||
}
|
||||
n.children = append(n.children, child)
|
||||
n.incrementChildPrio(len(n.indices) - 1)
|
||||
n = child
|
||||
}
|
||||
n.insertChild(numParams, path, fullPath, handle)
|
||||
return
|
||||
|
||||
} else if i == len(path) { // Make node a (in-path) leaf
|
||||
if n.handle != nil {
|
||||
panic("a handle is already registered for path '" + fullPath + "'")
|
||||
}
|
||||
n.handle = handle
|
||||
}
|
||||
return
|
||||
}
|
||||
} else { // Empty tree
|
||||
n.insertChild(numParams, path, fullPath, handle)
|
||||
n.nType = root
|
||||
}
|
||||
}
|
||||
|
||||
func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) {
|
||||
var offset int // already handled bytes of the path
|
||||
|
||||
// find prefix until first wildcard (beginning with ':'' or '*'')
|
||||
for i, max := 0, len(path); numParams > 0; i++ {
|
||||
c := path[i]
|
||||
if c != ':' && c != '*' {
|
||||
continue
|
||||
}
|
||||
|
||||
// find wildcard end (either '/' or path end)
|
||||
end := i + 1
|
||||
for end < max && path[end] != '/' {
|
||||
switch path[end] {
|
||||
// the wildcard name must not contain ':' and '*'
|
||||
case ':', '*':
|
||||
panic("only one wildcard per path segment is allowed, has: '" +
|
||||
path[i:] + "' in path '" + fullPath + "'")
|
||||
default:
|
||||
end++
|
||||
}
|
||||
}
|
||||
|
||||
// check if this Node existing children which would be
|
||||
// unreachable if we insert the wildcard here
|
||||
if len(n.children) > 0 {
|
||||
panic("wildcard route '" + path[i:end] +
|
||||
"' conflicts with existing children in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
// check if the wildcard has a name
|
||||
if end-i < 2 {
|
||||
panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
if c == ':' { // param
|
||||
// split path at the beginning of the wildcard
|
||||
if i > 0 {
|
||||
n.path = path[offset:i]
|
||||
offset = i
|
||||
}
|
||||
|
||||
child := &node{
|
||||
nType: param,
|
||||
maxParams: numParams,
|
||||
}
|
||||
n.children = []*node{child}
|
||||
n.wildChild = true
|
||||
n = child
|
||||
n.priority++
|
||||
numParams--
|
||||
|
||||
// if the path doesn't end with the wildcard, then there
|
||||
// will be another non-wildcard subpath starting with '/'
|
||||
if end < max {
|
||||
n.path = path[offset:end]
|
||||
offset = end
|
||||
|
||||
child := &node{
|
||||
maxParams: numParams,
|
||||
priority: 1,
|
||||
}
|
||||
n.children = []*node{child}
|
||||
n = child
|
||||
}
|
||||
|
||||
} else { // catchAll
|
||||
if end != max || numParams > 1 {
|
||||
panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
|
||||
panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
// currently fixed width 1 for '/'
|
||||
i--
|
||||
if path[i] != '/' {
|
||||
panic("no / before catch-all in path '" + fullPath + "'")
|
||||
}
|
||||
|
||||
n.path = path[offset:i]
|
||||
|
||||
// first node: catchAll node with empty path
|
||||
child := &node{
|
||||
wildChild: true,
|
||||
nType: catchAll,
|
||||
maxParams: 1,
|
||||
}
|
||||
// update maxParams of the parent node
|
||||
if n.maxParams < 1 {
|
||||
n.maxParams = 1
|
||||
}
|
||||
n.children = []*node{child}
|
||||
n.indices = string(path[i])
|
||||
n = child
|
||||
n.priority++
|
||||
|
||||
// second node: node holding the variable
|
||||
child = &node{
|
||||
path: path[i:],
|
||||
nType: catchAll,
|
||||
maxParams: 1,
|
||||
handle: handle,
|
||||
priority: 1,
|
||||
}
|
||||
n.children = []*node{child}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// insert remaining path part and handle to the leaf
|
||||
n.path = path[offset:]
|
||||
n.handle = handle
|
||||
}
|
||||
|
||||
// Returns the handle registered with the given path (key). The values of
|
||||
// wildcards are saved to a map.
|
||||
// If no handle can be found, a TSR (trailing slash redirect) recommendation is
|
||||
// made if a handle exists with an extra (without the) trailing slash for the
|
||||
// given path.
|
||||
func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) {
|
||||
walk: // outer loop for walking the tree
|
||||
for {
|
||||
if len(path) > len(n.path) {
|
||||
if path[:len(n.path)] == n.path {
|
||||
path = path[len(n.path):]
|
||||
// If this node does not have a wildcard (param or catchAll)
|
||||
// child, we can just look up the next child node and continue
|
||||
// to walk down the tree
|
||||
if !n.wildChild {
|
||||
c := path[0]
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if c == n.indices[i] {
|
||||
n = n.children[i]
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing found.
|
||||
// We can recommend to redirect to the same URL without a
|
||||
// trailing slash if a leaf exists for that path.
|
||||
tsr = (path == "/" && n.handle != nil)
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// handle wildcard child
|
||||
n = n.children[0]
|
||||
switch n.nType {
|
||||
case param:
|
||||
// find param end (either '/' or path end)
|
||||
end := 0
|
||||
for end < len(path) && path[end] != '/' {
|
||||
end++
|
||||
}
|
||||
|
||||
// save param value
|
||||
if p == nil {
|
||||
// lazy allocation
|
||||
p = make(Params, 0, n.maxParams)
|
||||
}
|
||||
i := len(p)
|
||||
p = p[:i+1] // expand slice within preallocated capacity
|
||||
p[i].Key = n.path[1:]
|
||||
p[i].Value = path[:end]
|
||||
|
||||
// we need to go deeper!
|
||||
if end < len(path) {
|
||||
if len(n.children) > 0 {
|
||||
path = path[end:]
|
||||
n = n.children[0]
|
||||
continue walk
|
||||
}
|
||||
|
||||
// ... but we can't
|
||||
tsr = (len(path) == end+1)
|
||||
return
|
||||
}
|
||||
|
||||
if handle = n.handle; handle != nil {
|
||||
return
|
||||
} else if len(n.children) == 1 {
|
||||
// No handle found. Check if a handle for this path + a
|
||||
// trailing slash exists for TSR recommendation
|
||||
n = n.children[0]
|
||||
tsr = (n.path == "/" && n.handle != nil)
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
case catchAll:
|
||||
// save param value
|
||||
if p == nil {
|
||||
// lazy allocation
|
||||
p = make(Params, 0, n.maxParams)
|
||||
}
|
||||
i := len(p)
|
||||
p = p[:i+1] // expand slice within preallocated capacity
|
||||
p[i].Key = n.path[2:]
|
||||
p[i].Value = path
|
||||
|
||||
handle = n.handle
|
||||
return
|
||||
|
||||
default:
|
||||
panic("invalid node type")
|
||||
}
|
||||
}
|
||||
} else if path == n.path {
|
||||
// We should have reached the node containing the handle.
|
||||
// Check if this node has a handle registered.
|
||||
if handle = n.handle; handle != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if path == "/" && n.wildChild && n.nType != root {
|
||||
tsr = true
|
||||
return
|
||||
}
|
||||
|
||||
// No handle found. Check if a handle for this path + a
|
||||
// trailing slash exists for trailing slash recommendation
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if n.indices[i] == '/' {
|
||||
n = n.children[i]
|
||||
tsr = (len(n.path) == 1 && n.handle != nil) ||
|
||||
(n.nType == catchAll && n.children[0].handle != nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Nothing found. We can recommend to redirect to the same URL with an
|
||||
// extra trailing slash if a leaf exists for that path
|
||||
tsr = (path == "/") ||
|
||||
(len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
|
||||
path == n.path[:len(n.path)-1] && n.handle != nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Makes a case-insensitive lookup of the given path and tries to find a handler.
|
||||
// It can optionally also fix trailing slashes.
|
||||
// It returns the case-corrected path and a bool indicating whether the lookup
|
||||
// was successful.
|
||||
func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
|
||||
return n.findCaseInsensitivePathRec(
|
||||
path,
|
||||
make([]byte, 0, len(path)+1), // preallocate enough memory for new path
|
||||
[4]byte{}, // empty rune buffer
|
||||
fixTrailingSlash,
|
||||
)
|
||||
}
|
||||
|
||||
// shift bytes in array by n bytes left
|
||||
func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
|
||||
switch n {
|
||||
case 0:
|
||||
return rb
|
||||
case 1:
|
||||
return [4]byte{rb[1], rb[2], rb[3], 0}
|
||||
case 2:
|
||||
return [4]byte{rb[2], rb[3]}
|
||||
case 3:
|
||||
return [4]byte{rb[3]}
|
||||
default:
|
||||
return [4]byte{}
|
||||
}
|
||||
}
|
||||
|
||||
// recursive case-insensitive lookup function used by n.findCaseInsensitivePath
|
||||
func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) ([]byte, bool) {
|
||||
npLen := len(n.path)
|
||||
|
||||
walk: // outer loop for walking the tree
|
||||
for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {
|
||||
// add common prefix to result
|
||||
|
||||
oldPath := path
|
||||
path = path[npLen:]
|
||||
ciPath = append(ciPath, n.path...)
|
||||
|
||||
if len(path) > 0 {
|
||||
// If this node does not have a wildcard (param or catchAll) child,
|
||||
// we can just look up the next child node and continue to walk down
|
||||
// the tree
|
||||
if !n.wildChild {
|
||||
// skip rune bytes already processed
|
||||
rb = shiftNRuneBytes(rb, npLen)
|
||||
|
||||
if rb[0] != 0 {
|
||||
// old rune not finished
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if n.indices[i] == rb[0] {
|
||||
// continue with child node
|
||||
n = n.children[i]
|
||||
npLen = len(n.path)
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// process a new rune
|
||||
var rv rune
|
||||
|
||||
// find rune start
|
||||
// runes are up to 4 byte long,
|
||||
// -4 would definitely be another rune
|
||||
var off int
|
||||
for max := min(npLen, 3); off < max; off++ {
|
||||
if i := npLen - off; utf8.RuneStart(oldPath[i]) {
|
||||
// read rune from cached path
|
||||
rv, _ = utf8.DecodeRuneInString(oldPath[i:])
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// calculate lowercase bytes of current rune
|
||||
lo := unicode.ToLower(rv)
|
||||
utf8.EncodeRune(rb[:], lo)
|
||||
|
||||
// skip already processed bytes
|
||||
rb = shiftNRuneBytes(rb, off)
|
||||
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
// lowercase matches
|
||||
if n.indices[i] == rb[0] {
|
||||
// must use a recursive approach since both the
|
||||
// uppercase byte and the lowercase byte might exist
|
||||
// as an index
|
||||
if out, found := n.children[i].findCaseInsensitivePathRec(
|
||||
path, ciPath, rb, fixTrailingSlash,
|
||||
); found {
|
||||
return out, true
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// if we found no match, the same for the uppercase rune,
|
||||
// if it differs
|
||||
if up := unicode.ToUpper(rv); up != lo {
|
||||
utf8.EncodeRune(rb[:], up)
|
||||
rb = shiftNRuneBytes(rb, off)
|
||||
|
||||
for i, c := 0, rb[0]; i < len(n.indices); i++ {
|
||||
// uppercase matches
|
||||
if n.indices[i] == c {
|
||||
// continue with child node
|
||||
n = n.children[i]
|
||||
npLen = len(n.path)
|
||||
continue walk
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing found. We can recommend to redirect to the same URL
|
||||
// without a trailing slash if a leaf exists for that path
|
||||
return ciPath, (fixTrailingSlash && path == "/" && n.handle != nil)
|
||||
}
|
||||
|
||||
n = n.children[0]
|
||||
switch n.nType {
|
||||
case param:
|
||||
// find param end (either '/' or path end)
|
||||
k := 0
|
||||
for k < len(path) && path[k] != '/' {
|
||||
k++
|
||||
}
|
||||
|
||||
// add param value to case insensitive path
|
||||
ciPath = append(ciPath, path[:k]...)
|
||||
|
||||
// we need to go deeper!
|
||||
if k < len(path) {
|
||||
if len(n.children) > 0 {
|
||||
// continue with child node
|
||||
n = n.children[0]
|
||||
npLen = len(n.path)
|
||||
path = path[k:]
|
||||
continue
|
||||
}
|
||||
|
||||
// ... but we can't
|
||||
if fixTrailingSlash && len(path) == k+1 {
|
||||
return ciPath, true
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
||||
|
||||
if n.handle != nil {
|
||||
return ciPath, true
|
||||
} else if fixTrailingSlash && len(n.children) == 1 {
|
||||
// No handle found. Check if a handle for this path + a
|
||||
// trailing slash exists
|
||||
n = n.children[0]
|
||||
if n.path == "/" && n.handle != nil {
|
||||
return append(ciPath, '/'), true
|
||||
}
|
||||
}
|
||||
return ciPath, false
|
||||
|
||||
case catchAll:
|
||||
return append(ciPath, path...), true
|
||||
|
||||
default:
|
||||
panic("invalid node type")
|
||||
}
|
||||
} else {
|
||||
// We should have reached the node containing the handle.
|
||||
// Check if this node has a handle registered.
|
||||
if n.handle != nil {
|
||||
return ciPath, true
|
||||
}
|
||||
|
||||
// No handle found.
|
||||
// Try to fix the path by adding a trailing slash
|
||||
if fixTrailingSlash {
|
||||
for i := 0; i < len(n.indices); i++ {
|
||||
if n.indices[i] == '/' {
|
||||
n = n.children[i]
|
||||
if (len(n.path) == 1 && n.handle != nil) ||
|
||||
(n.nType == catchAll && n.children[0].handle != nil) {
|
||||
return append(ciPath, '/'), true
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
||||
}
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing found.
|
||||
// Try to fix the path by adding / removing a trailing slash
|
||||
if fixTrailingSlash {
|
||||
if path == "/" {
|
||||
return ciPath, true
|
||||
}
|
||||
if len(path)+1 == npLen && n.path[len(path)] == '/' &&
|
||||
strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handle != nil {
|
||||
return append(ciPath, n.path...), true
|
||||
}
|
||||
}
|
||||
return ciPath, false
|
||||
}
|
|
@ -7,6 +7,9 @@ github.com/h2non/filetype/types
|
|||
# github.com/inconshreveable/mousetrap v1.1.0
|
||||
## explicit; go 1.18
|
||||
github.com/inconshreveable/mousetrap
|
||||
# github.com/julienschmidt/httprouter v1.3.0
|
||||
## explicit; go 1.7
|
||||
github.com/julienschmidt/httprouter
|
||||
# github.com/klauspost/compress v1.16.5
|
||||
## explicit; go 1.18
|
||||
github.com/klauspost/compress
|
||||
|
|
Loading…
Reference in New Issue