errhandler

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 15, 2024 License: MIT Imports: 2 Imported by: 1

README

errhandler

Wraps Go's http.HandlerFunc, allowing for simpler use of http.NewServeMux().

Install
go get github.com/codingconcepts/errhandler
Usage

Wrap Go's stdlib http.HandlerFunc using errhandler.Wrap():

mux := http.NewServeMux()
mux.Handle("GET /products", errhandler.Wrap(addProduct))

Update your existing handler signatures, by adding an error return type and utilizing the optional errhandler.ParseJSON and errhandler.SendJSON helper functions to reduce the amount of boilerplate code handlers require:

func addProduct(w http.ResponseWriter, r *http.Request) error {
  var p product
  if err := errhandler.ParseJSON(r, &p); err != nil {
    return SendError(w, http.StatusUnprocessableEntity, err)
  }
  
  products[p.ID] = p
  
  return errhandler.SendJSON(w, p)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseJSON

func ParseJSON(r *http.Request, val any) error

ParseJSON can be used to parse a string from the body of a request.

func SendError added in v0.0.3

func SendError(w http.ResponseWriter, code int, err error) error

SendError returns an error response to the caller, or fails with an error.

func SendJSON

func SendJSON(w http.ResponseWriter, data interface{}) error

SendJSON returns a JSON response to the caller, or fails with an error.

func SendString

func SendString(w http.ResponseWriter, message string) error

SendString returns a string response to the caller, or fails with an error.

Types

type Wrap

type Wrap func(w http.ResponseWriter, r *http.Request) error

Wrap an http.HandlerFunc, allowing for errors to be handled in a more familiar way inside your handlers.

func (Wrap) ServeHTTP

func (fn Wrap) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is invoked when the HTTP handler is called, capturing and returning any errors encountered in the ErrHandlerFunc.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL