jh

package module
v0.0.0-...-4535806 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2022 License: MIT Imports: 6 Imported by: 0

README

https://pkg.go.dev/github.com/ryandotsmith/jh

Documentation

Overview

This package helps you encode/decode JSON from HTTP request/response into Go structs.

type req struct {
	X, Y int
}

type resp struct {
	Sum int
}

func add(ctx context.Context, r req) (*resp, error) {
	return &resp{r.X+r.Y}, nil
}

http.Handle("/add", Handler(add), ErrHandler)

In this example, add is a wrapped function that jh will use to determine how to encode/decode json.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTooFewArgs  = errors.New("jh: handler: too few args. expected wrappedFunc with at least 1 arg")
	ErrTooManyArgs = errors.New("jh: handler: too many args. expected wrappedFunc with no more than 2 args")
	ErrMissingCtx  = errors.New("jh: handler: 1st arg must be context.Context")
	ErrNumRet      = errors.New("jh: handler: expected wrappedFunc to have 2 return values")
	ErrMissingErr  = errors.New("jh: handler: wrappedFunc's 2nd return value must be an error")
)

Functions

func ErrHandler

func ErrHandler(ctx context.Context, w http.ResponseWriter, err error)

func Handler

func Handler(
	wrappedFunc any,
	errFunc func(context.Context, http.ResponseWriter, error),
) (http.Handler, error)

Reflection is used on wrappedFunc to determine the req/resp types for later json encoding/decoding. An error is returned when wrappedFunc doesn't conform to one of the following forms:

func(context.Context, struct{}) (*struct{}, error)
func(context.Context) (*struct{}, error)

errFunc is called when a wrappedFunc returns an error or when json encoding/decdoing encounters an error.

func Request

func Request(ctx context.Context) *http.Request

Can be used inside of a wrapped function. eg parsing url parameters

func ResponseWriter

func ResponseWriter(ctx context.Context) http.ResponseWriter

Can be used inside of a wrapped function. eg setting a response header

Types

type Error

type Error struct {
	Code    int    `json:"-"`
	Message string `json:"message"`
}

func (Error) Error

func (e Error) Error() string

Jump to

Keyboard shortcuts

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