Skip to content

Getting started

gorouter sends each HTTP request to a handler chosen by its method and path. It works with the standard net/http package and with fasthttp, with the same API and the same matching rules for both.

gorouter needs Go 1.26 or newer.

Terminal window
go get github.com/vardius/gorouter/v5

The fasthttp router lives in its own package, github.com/vardius/gorouter/v5/fastrouter, so a net/http program never links fasthttp.

examples/hello/main.go
// Command hello is the smallest gorouter server: a few routes, a param and a regexp param.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/vardius/gorouter/v5"
)
func newRouter() *gorouter.Router {
r := gorouter.New()
r.GET("/", index)
r.GET("/hello/{name}", hello)
r.GET("/users/{id:[0-9]+}", user)
return r
}
func index(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "welcome")
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello, %s!\n", r.PathValue("name"))
}
func user(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "user #%s\n", r.PathValue("id"))
}
func main() {
srv := &http.Server{Addr: ":8080", Handler: newRouter(), ReadHeaderTimeout: 5 * time.Second}
log.Fatal(srv.ListenAndServe())
}
  1. From a clone of the repository, start the server:

    Terminal window
    go run ./examples/hello

    For the fasthttp version, run go run ./examples/fasthttp instead.

  2. In another terminal, call a route with a param:

    Terminal window
    curl localhost:8080/hello/gopher
    hello, gopher!
  3. Try the regexp param. /users/42 matches {id:[0-9]+}; /users/gopher doesn’t, so it gets a 404:

    Terminal window
    curl -i localhost:8080/users/gopher
    HTTP/1.1 404 Not Found
  • gorouter.New() returns a *gorouter.Router. It is an http.Handler, so it plugs into http.Server like any other.
  • r.GET registers a handler func for GET. There is a helper for every standard method, and r.Handle takes any http.Handler on any method, custom ones included.
  • {name} matches any one path segment. Read its value with r.PathValue("name").
  • {id:[0-9]+} matches a segment only when the whole segment matches the regexp.
  • A path no route matches gets 404 Not Found. A path that only matches on other methods gets 405 Method Not Allowed, with an Allow header listing them.