matheusd/jolde

The simplest JSON-based Go HTTP framework.

★ 0Forks 0GoGitHub ↗Compare

README

jolde

jolde is a small Go library for building JSON HTTP APIs. It wraps net/http handlers with typed request/response decoding, structured error handling, and request logging.

Usage

Define request and response types, then wrap a handler with StdWrap:

type EchoRequest  struct { Message string `json:"message"` }
type EchoResponse struct { Echo    string `json:"echo"`    }

func echoHandler(rc jolde.ReqContext, req *EchoRequest) (*EchoResponse, error) {
    return &EchoResponse{Echo: req.Message}, nil
}

http.HandleFunc("/echo", jolde.StdWrap(echoHandler))

StdWrap decodes the JSON request body into ReqT, calls the handler, and encodes the returned value as the JSON response. Errors returned by the handler produce a 500 response; decoding failures produce a 400.

Custom configuration

StdWrap uses StdWC, a pre-built WrapperConfig. You can define your own to override any of the callbacks:

wc := jolde.WrapperConfig{
    DecodeError:  myDecodeError,
    HandlerError: myHandlerError,
    EncodeError:  myEncodeError,
    Recover:      myRecover,
    Finished:     myFinished,
}
http.HandleFunc("/echo", jolde.Wrap(wc, echoHandler))

Callbacks

Field Default Called when
DecodeError StdDecodeError request body cannot be decoded (returns 400)
HandlerError StdHandlerError handler returns an error (returns 500)
EncodeError StdEncodeError response cannot be encoded (returns 500)
Recover StdRecover handler panics; if nil the panic propagates
Finished StdFinished request completes, regardless of outcome

HTTP status override

Any error can implement HttpStatuser to override the default status code:

type HttpStatuser interface {
    HttpStatus() jolde.HttpStatus
}

Example

See examples/simple for a runnable server demonstrating a successful response, a handler error, and a panic recovery.

License

ISC — see LICENSE.

Contributors

matheusd

Issues