The Central Go Modules Repository

To use GoCenter:
export GOPROXY=https://gocenter.io
0
Stars
BSD-3-Clause
License
4
Downloads
April 12th 2020
Last Modified
Version:
Loading...

httprouter: HTTP router GoDoc Travis CI

Basic HTTP router for Go.

Example

The following code:

package main

import (
        "fmt"
        "log"
        "net/http"

        "batou.dev/httprouter"
)

func main() {
        r := httprouter.NewRouter()

        r.Endpoint("/foo").
                Get(handleFoo).
                Post(handleFoo)
        r.Endpoint("/bar/:baz").
                Get(handleBar)
        r.Endpoint("/*").
                Get(handleDefault)

        s := &http.Server{
                Addr:    ":8080",
                Handler: r,
        }

        err := s.ListenAndServe()
        if err != nil {
                log.Fatal(err)
        }
}

func handleBar(rw http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(rw, "Received %q\n", httprouter.ContextParam(r, "baz").(string))
}

func handleDefault(rw http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(rw, "Default here!")
}

func handleFoo(rw http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(rw, "Received %q request\n", r.Method)
}

will give you:

# curl http://localhost:8080/foo
Received "GET" request

# curl -X POST http://localhost:8080/foo
Received "POST" request

# curl http://localhost:8080/bar/baz
Received "baz"

# curl http://localhost:8080/
Default here!