httpwr
is an extended and modified version of this repository.
The idea is still the same, that is to force the return type to the http handler, so we can minimize the risk of putting return state.
func someHandler(w http.ResponseWriter, r *http.Request) {
err := doSomethingThatReturnError()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
// forgot to return here
}
doJob()
}
Basic usages:
- Return error from handler
func someFunction() error {
return errors.New("error messages")
}
func main() {
router := http.NewServeMux()
router.Handle("/test", httpwr.F(func(w http.ResponseWriter, r *http.Request) error {
err := someFunction()
return err
}))
}
{
"status": 500,
"error": "error messages"
}
- Return error with status code
func someFunction() error {
return errors.New("error messages")
}
func main() {
router := http.NewServeMux()
router.Handle("/test", httpwr.F(func(w http.ResponseWriter, r *http.Request) error {
err := someFunction()
return httpwr.Wrap(http.StatusBadRequest, err)
}))
}
{
"status": 400,
"error": "error messages"
}
- Return error with
errorf
:
func someFunction() error {
return errors.New("error messages")
}
func main() {
router := http.NewServeMux()
router.Handle("/test", httpwr.F(func(w http.ResponseWriter, r *http.Request) error {
err := someFunction()
return httpwr.Wrap(http.StatusBadRequest, err)
}))
}
{
"status": 400,
"error": "something wrong: i dont know message"
}
- No Error in handler? You can return
httpwr.OK
func main() {
router := http.NewServeMux()
router.Handle("/test", httpwr.F(func(w http.ResponseWriter, r *http.Request) error {
return httpwr.OK(http.StatusOK, "all good")
}))
}
{
"status": 200,
"msg": "all good"
}
- Want to return OK with Data? Use
httpwr.OKWithData
func main() {
router := http.NewServeMux()
router.Handle("/test", httpwr.F(func(w http.ResponseWriter, r *http.Request) error {
data := M{"some": "data"}
return httpwr.OKWithData(http.StatusOK, "all good", data)
}))
}
{
"status": 200,
"msg": "all good"
"data": {
"some": "data",
}
}
httpwr.M
is an alias for map[string]any