Basic HTTP router for Go.
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!