errhandler

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 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/{id}", errhandler.Wrap(getProduct))

Update your existing handler signature, by adding an error return type:

func addProduct(w http.ResponseWriter, r *http.Request) error {
	...
}

Utilize the ParseJSON and SendJSON functions to reduce the amount of boilerplate code handlers require:

var p product
if err := errhandler.ParseJSON(r, &p); err != nil {
  return fmt.Errorf("parsing request json: %w", 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 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