router/default.go

42 lines
856 B
Go

package router
import (
"encoding/json"
"fmt"
"net/http"
)
func defaultNotFoundHandler(c *Context) error {
return c.StatusText(http.StatusNotFound)
}
func defaultMethodNotAllowedHandler(c *Context) error {
return c.StatusText(http.StatusMethodNotAllowed)
}
func defaultErrorHandler(c *Context, err interface{}) {
fmt.Printf("%s '%s': %s\n", c.Request.Method, c.Request.URL, err)
_ = c.StatusText(http.StatusInternalServerError)
}
func defaultBadRequestFormatter(c *Context, reason string) error {
return c.String(http.StatusBadRequest, reason)
}
func BodyJSON[T any](handle func(*Context, T) error) Handle {
return func(c *Context) error {
var dst T
err := json.NewDecoder(c.Request.Body).Decode(&dst)
if err != nil {
return c.BadRequest(`Invalid JSON`)
}
if !c.Validate(dst) {
return nil
}
return handle(c, dst)
}
}