[][src]Module httprouter::router

Httprouter is a trie based high performance HTTP request router.

A trivial example is:

This example is not tested
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, 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/rust/request-routers match: category="rust", post="request-routers" /blog/rust/request-routers/ no match, but the router would redirect /blog/rust/ no match /blog/rust/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 let user = params.by_name("user") // defined by :user or *user

// by the index of the parameter. This way you can also get the name (key) thirdKey := params[2].key // the name of the 3rd parameter thirdValue := params[2].value // the value of the 3rd parameter

Structs

Router

Router is container which can be used to dispatch requests to different handler functions via configurable routes

Traits

Handle