visit
gin.Context
or echo.Context
).
BunRouter uses a slightly enhanced version of http.HandlerFunc that accepts a bunrouter.Request
and returns errors that you can handle with middlewares:
import "github.com/uptrace/bunrouter"
router := bunrouter.New(
bunrouter.Use(reqlog.NewMiddleware()),
)
router.WithGroup("/api", func(g *bunrouter.Group) {
g.GET("/users/:id", debugHandler)
g.GET("/users/current", debugHandler)
g.GET("/users/*path", debugHandler)
})
func debugHandler(w http.ResponseWriter, req bunrouter.Request) error {
// use req.Request to get *http.Request
return bunrouter.JSON(w, bunrouter.H{
"route": req.Route(),
"params": req.Params().Map(),
})
}
:param
is a named parameter that matches a single path segment (text between slashes).*param
is a wildcard parameter that matches everything and must always be at the end of the route.
func middleware(next bunrouter.HandlerFunc) bunrouter.HandlerFunc {
// you can initialize the middleware here
// Return the middleware.
return func(w http.ResponseWriter, req bunrouter.Request) error {
rec := httptest.NewRecorder()
// Pass the recorder instead of http.ResponseWriter.
if err := next(rec, req); err != nil {
fmt.Printf("%s %s failed: %s\n", req.Method, req.Route(), err)
// Discard the error.
return nil
}
fmt.Printf("%s %s returned %d\n", req.Method, req.Route(), rec.Code)
}
}
router.Use(middleware).WithGroup(...)
func errorHandler(next bunrouter.HandlerFunc) bunrouter.HandlerFunc {
return func(w http.ResponseWriter, req bunrouter.Request) error {
// Call the next handler on the chain to get the error.
err := next(w, req)
switch err := err.(type) {
case nil:
// no error
case HTTPError: // already a HTTPError
w.WriteHeader(err.statusCode)
_ = bunrouter.JSON(w, err)
default:
httpErr := NewHTTPError(err)
w.WriteHeader(httpErr.statusCode)
_ = bunrouter.JSON(w, httpErr)
}
return err // return the err in case there other middlewares
}
}
Static nodes, for example, /users/
Named nodes, for example, :id
.
Wildcard nodes, for example, *path
.
/users/list
./users/:id
./users/*path
.