A http router utility for golang net/http library which can be used either as a mux or as a standalone router
router := gohttprouter.NewRouter()
router.GET("/", handler) // handler should match signature - func (http.ResponseWriter, *http.Request) {}
router.POST("/save", saveHandler)
http.ListenAndServe(port, router)
GET, POST, PUT, PATCH, DELETE
Dynamic route can be defined by prefixing a path value with a colon. For eg, router.GET("/view/:title") will allow all routing that matches /view/*. To fetch the dynamic value, *http.Request's PathValue method can be used
import (
"fmt"
"net/http"
"github.com/blackistheneworange/gohttprouter"
)
func myHandler(w http.ResponseWriter, r *http.Request) {
title := r.PathValue("title")
fmt.Fprintf(w, "Page title: %s", title)
}
func main() {
router := gohttprouter.NewRouter()
router.GET("/view/:title", myHandler)
http.ListenAndServe(":8080", router)
}
Middleware handlers are allowed to be passed in any of the available methods in between the route path and http handler.
A middleware handler should match the following signature
func (http.ResponseWriter, *http.Request, gohttprouter.NextFunction) {}
import (
"fmt"
"net/http"
"github.com/blackistheneworange/gohttprouter"
)
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!")
}
func customMiddleware(w http.ResponseWriter, r *http.Request, next gohttprouter.NextFunction) {
// some actions
next(w, r)
}
func main() {
router := gohttprouter.NewRouter()
router.GET("/", customMiddleware, myHandler)
http.ListenAndServe(":8080", router)
}