Skip to content

Latest commit

 

History

History
139 lines (109 loc) · 2.71 KB

README.md

File metadata and controls

139 lines (109 loc) · 2.71 KB

httpwr

Build Status Coverage Go Report Card

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:

  1. 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"
}
  1. 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"
}
  1. 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"
}
  1. 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"
}
  1. 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