router

package
v1.2.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: Apache-2.0, BSD-3-Clause Imports: 9 Imported by: 0

README

fasthttprouter

A fork of fasthttp/router v1.5.4 that routes for this repository's fasthttp fork. It is a drop-in replacement: change the import path and nothing else. The package is still named router, so code reads exactly as it does with upstream.

import router "github.com/shibukawa/tinygodriver/fasthttprouter"

Upstream cannot be used here even though it compiles under standard Go: it registers handlers against github.com/valyala/fasthttp, and Go treats its RequestHandler and the fork's as unrelated types. This fork is that one import rewritten — the non-test sources carry zero patches beyond it, and PATCHES.md records the two test-only fixes. The full upstream test suite is vendored and passes under both compilers.

If an application targets standard Go only, use upstream fasthttp/router with upstream fasthttp; this fork is for TinyGo builds and for code shared across both compilers.

Licence

This directory is BSD-3-Clause, not the Apache 2.0 of the rest of the repository nor the MIT of fasthttp/. LICENSE is upstream's own.

Quick start

No build tags are needed on either compiler. The fasthttp fork pulls in the compression stack, and it encodes zstd through compress/zstd under TinyGo; -tags fasthttp_nozstd drops zstd if the last 0.05 MB matters.

package main

import (
	"fmt"

	"github.com/shibukawa/tinygodriver/fasthttp"
	router "github.com/shibukawa/tinygodriver/fasthttprouter"
	_ "github.com/shibukawa/tinygodriver/netdev"
)

func main() {
	r := router.New()
	r.GET("/hello/{name}", func(ctx *fasthttp.RequestCtx) {
		fmt.Fprintf(ctx, "hello, %s!\n", ctx.UserValue("name"))
	})
	fasthttp.ListenAndServe(":8080", r.Handler)
}

examples/fasthttpserver uses this router on both compilers, wildcard static route included.

Cost

Adding the router to that example's TinyGo build (-tags fasthttp_nozstd, darwin/arm64) grew the binary from 3.07 MB to 3.33 MB. The 0.26 MB is the router, its radix tree, savsgio/gotils, and regexp — which the router pulls in for {param:regex} routes whether or not any route uses one.

Vendoring

python3 vendor.py re-vendors from the module cache after bumping ROUTER_VERSION — run go mod download github.com/fasthttp/router@<version> first. The script copies the root package and radix, tests included, rewrites the imports, and applies the PATCHES.md edits with exact-occurrence checks.

TinyGo quirk worth knowing if the tests ever grow: reflect.Value.Pointer() on a func is unreliable there, which is why handler identity goes through the sameHandler helper — see PATCHES.md §2.

Documentation

Overview

Package router is a trie based high performance HTTP request router.

A trivial example is:

package main

import (
    "fmt"
    "log"

    "github.com/shibukawa/tinygodriver/fasthttprouter"
)

func Index(ctx *fasthttp.RequestCtx) {
    fmt.Fprint(w, "Welcome!\n")
}

func Hello(ctx *fasthttp.RequestCtx) {
    fmt.Fprintf(w, "hello, %s!\n", ctx.UserValue("name"))
}

func main() {
    r := router.New()
    r.GET("/", Index)
    r.GET("/hello/{name}", Hello)

    log.Fatal(fasthttp.ListenAndServe(":8080", r.Handler))
}

The router matches incoming requests by the request method and the path. If a handler is registered for this path and method, the router delegates the request to that function. For the methods GET, POST, PUT, PATCH, DELETE and OPTIONS 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. Since they match anything until the end, catch-all parameters must always be the final path element.

The matched value carries no leading slash, and the directory index yields the empty string. Upstream httprouter documents a leading slash here; this router does not produce one, and neither does net/http's ServeMux for the equivalent {filepath...} pattern.

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 in ctx.UserValue(<key>), consisting each of a key and a value. The slice is passed to the Handle func as a third parameter. To retrieve the value of a parameter,gets by the name of the parameter

user := ctx.UserValue("user") // defined by {user} or {user:*}

Index

Constants

View Source
const MethodWild = "*"

MethodWild wild HTTP method

Variables

View Source
var (

	// MatchedRoutePathParam is the param name under which the path of the matched
	// route is stored, if Router.SaveMatchedRoutePath is set.
	MatchedRoutePathParam = fmt.Sprintf("__matchedRoutePath::%s__", bytes.Rand(make([]byte, 15)))
)

Functions

This section is empty.

Types

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group is a sub-router to group paths

func (*Group) ANY

func (g *Group) ANY(path string, handler fasthttp.RequestHandler)

ANY is a shortcut for group.Handle(router.MethodWild, path, handler)

WARNING: Use only for routes where the request method is not important

func (*Group) CONNECT

func (g *Group) CONNECT(path string, handler fasthttp.RequestHandler)

OPTIONS is a shortcut for group.Handle(fasthttp.MethodOptions, path, handler)

func (*Group) DELETE

func (g *Group) DELETE(path string, handler fasthttp.RequestHandler)

DELETE is a shortcut for group.Handle(fasthttp.MethodDelete, path, handler)

func (*Group) GET

func (g *Group) GET(path string, handler fasthttp.RequestHandler)

GET is a shortcut for group.Handle(fasthttp.MethodGet, path, handler)

func (*Group) Group

func (g *Group) Group(path string) *Group

Group returns a new group. Path auto-correction, including trailing slashes, is enabled by default.

func (*Group) HEAD

func (g *Group) HEAD(path string, handler fasthttp.RequestHandler)

HEAD is a shortcut for group.Handle(fasthttp.MethodHead, path, handler)

func (*Group) Handle

func (g *Group) Handle(method, path string, handler fasthttp.RequestHandler)

Handle registers a new request handler 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 (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handler fasthttp.RequestHandler)

OPTIONS is a shortcut for group.Handle(fasthttp.MethodOptions, path, handler)

func (*Group) PATCH

func (g *Group) PATCH(path string, handler fasthttp.RequestHandler)

PATCH is a shortcut for group.Handle(fasthttp.MethodPatch, path, handler)

func (*Group) POST

func (g *Group) POST(path string, handler fasthttp.RequestHandler)

POST is a shortcut for group.Handle(fasthttp.MethodPost, path, handler)

func (*Group) PUT

func (g *Group) PUT(path string, handler fasthttp.RequestHandler)

PUT is a shortcut for group.Handle(fasthttp.MethodPut, path, handler)

func (*Group) ServeFS

func (g *Group) ServeFS(path string, filesystem fs.FS)

ServeFS serves files from the given file system. 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 fasthttp.FSHandler is used, therefore http.NotFound is used instead Use:

router.ServeFS("/src/{filepath:*}", myFilesystem)

func (*Group) ServeFiles

func (g *Group) ServeFiles(path string, rootPath string)

ServeFiles serves files from the given file system root path. 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 fasthttp.FSHandler is used, therefore http.NotFound is used instead Use:

router.ServeFiles("/src/{filepath:*}", "./")

func (*Group) ServeFilesCustom

func (g *Group) ServeFilesCustom(path string, fs *fasthttp.FS)

ServeFilesCustom serves files from the given file system settings. 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 fasthttp.FSHandler is used, therefore http.NotFound is used instead of the Router's NotFound handler. Use:

router.ServeFilesCustom("/src/{filepath:*}", *customFS)

func (*Group) TRACE

func (g *Group) TRACE(path string, handler fasthttp.RequestHandler)

OPTIONS is a shortcut for group.Handle(fasthttp.MethodOptions, path, handler)

type Router

type Router struct {

	// If enabled, adds the matched route path onto the ctx.UserValue context
	// before invoking the handler.
	// The matched route path is only added to handlers of routes that were
	// registered when this option was enabled.
	SaveMatchedRoutePath bool

	// 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 308 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 308 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 fasthttp.RequestHandler 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 fasthttp.RequestHandler

	// Configurable fasthttp.RequestHandler which is called when no matching route is
	// found. If it is not set, default NotFound is used.
	NotFound fasthttp.RequestHandler

	// Configurable fasthttp.RequestHandler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, ctx.Error with fasthttp.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed fasthttp.RequestHandler

	// 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(*fasthttp.RequestCtx, interface{})
	// contains filtered or unexported fields
}

Router is a fasthttp.RequestHandler which can be used to dispatch requests to different handler functions via configurable routes

func New

func New() *Router

New returns a new router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) ANY

func (r *Router) ANY(path string, handler fasthttp.RequestHandler)

ANY is a shortcut for router.Handle(router.MethodWild, path, handler)

WARNING: Use only for routes where the request method is not important

func (*Router) CONNECT

func (r *Router) CONNECT(path string, handler fasthttp.RequestHandler)

CONNECT is a shortcut for router.Handle(fasthttp.MethodConnect, path, handler)

func (*Router) DELETE

func (r *Router) DELETE(path string, handler fasthttp.RequestHandler)

DELETE is a shortcut for router.Handle(fasthttp.MethodDelete, path, handler)

func (*Router) GET

func (r *Router) GET(path string, handler fasthttp.RequestHandler)

GET is a shortcut for router.Handle(fasthttp.MethodGet, path, handler)

func (*Router) Group

func (r *Router) Group(path string) *Group

Group returns a new group. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) HEAD

func (r *Router) HEAD(path string, handler fasthttp.RequestHandler)

HEAD is a shortcut for router.Handle(fasthttp.MethodHead, path, handler)

func (*Router) Handle

func (r *Router) Handle(method, path string, handler fasthttp.RequestHandler)

Handle registers a new request handler 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 (*Router) Handler

func (r *Router) Handler(ctx *fasthttp.RequestCtx)

Handler makes the router implement the http.Handler interface.

func (*Router) List

func (r *Router) List() map[string][]string

List returns all registered routes grouped by method

func (*Router) Lookup

func (r *Router) Lookup(method, path string, ctx *fasthttp.RequestCtx) (fasthttp.RequestHandler, bool)

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 handler function. Otherwise the second return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) Mutable

func (r *Router) Mutable(v bool)

Mutable allows updating the route handler

It's disabled by default

WARNING: Use with care. It could generate unexpected behaviours

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler fasthttp.RequestHandler)

OPTIONS is a shortcut for router.Handle(fasthttp.MethodOptions, path, handler)

func (*Router) PATCH

func (r *Router) PATCH(path string, handler fasthttp.RequestHandler)

PATCH is a shortcut for router.Handle(fasthttp.MethodPatch, path, handler)

func (*Router) POST

func (r *Router) POST(path string, handler fasthttp.RequestHandler)

POST is a shortcut for router.Handle(fasthttp.MethodPost, path, handler)

func (*Router) PUT

func (r *Router) PUT(path string, handler fasthttp.RequestHandler)

PUT is a shortcut for router.Handle(fasthttp.MethodPut, path, handler)

func (*Router) ServeFS

func (r *Router) ServeFS(path string, filesystem fs.FS)

ServeFS serves files from the given file system. 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 fasthttp.FSHandler is used, therefore fasthttp.NotFound is used instead Use:

router.ServeFS("/src/{filepath:*}", myFilesystem)

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, rootPath string)

ServeFiles serves files from the given file system root path. 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 fasthttp.FSHandler is used, therefore fasthttp.NotFound is used instead Use:

router.ServeFiles("/src/{filepath:*}", "./")

func (*Router) ServeFilesCustom

func (r *Router) ServeFilesCustom(path string, fs *fasthttp.FS)

ServeFilesCustom serves files from the given file system settings. 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 fasthttp.FSHandler is used, therefore http.NotFound is used instead of the Router's NotFound handler. Use:

router.ServeFilesCustom("/src/{filepath:*}", *customFS)

func (*Router) TRACE

func (r *Router) TRACE(path string, handler fasthttp.RequestHandler)

TRACE is a shortcut for router.Handle(fasthttp.MethodTrace, path, handler)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL