- Notifications
You must be signed in to change notification settings - Fork17
A lightweight Go library for writing responses and errors to HTTP
License
ory/herodot
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Herodot is a lightweight SDK for writing RESTful responses. It is comparable torender but provides easier error handling.The error model implements the well establishedGoogle API Design Guide. Herodotcurrently supports only JSON responses but can be extended easily.
Herodot is used byORY Hydra and serves millionsof requests already.
Herodot is versioned usinggo modules and works best withpkg/errors. To install it, run
go get -u github.com/ory/herodot
Tips on upgrading can be found inUPGRADE.md
Using Herodot is straightforward. The examples below will help you get started.
Herodot supplies an interface, allowing to return errors in many data formatslike XML and others. Currently, it supports only JSON.
varhd=herodot.NewJSONWriter(nil)funcGetHandler(rw http.ResponseWriter,r*http.Request) {// run your business logic herehd.Write(rw,r,map[string]interface{}{"key":"value"})}typeMyStructstruct {Keystring`json:"key"`}funcGetHandlerWithStruct(rw http.ResponseWriter,r*http.Request) {// business logichd.Write(rw,r,&MyStruct{Key:"value"})}funcPostHandlerWithStruct(rw http.ResponseWriter,r*http.Request) {// business logichd.WriteCreated(rw,r,"/path/to/the/resource/that/was/created",&MyStruct{Key:"value"})}funcSomeHandlerWithArbitraryStatusCode(rw http.ResponseWriter,r*http.Request) {// business logichd.WriteCode(rw,r,http.StatusAccepted,&MyStruct{Key:"value"})}funcSomeHandlerWithArbitraryStatusCode(rw http.ResponseWriter,r*http.Request) {// business logichd.WriteCode(rw,r,http.StatusAccepted,&MyStruct{Key:"value"})}
varwriter=herodot.NewJSONWriter(nil)funcGetHandlerWithError(rw http.ResponseWriter,r*http.Request) {iferr:=someFunctionThatReturnsAnError();err!=nil {hd.WriteError(w,r,err)return }// ...}funcGetHandlerWithErrorCode(rw http.ResponseWriter,r*http.Request) {iferr:=someFunctionThatReturnsAnError();err!=nil {hd.WriteErrorCode(w,r,http.StatusBadRequest,err)return }// ...}
Herodot implements the error model of the well establishedGoogle API Design Guide.Additionally, it makes the fieldsrequest
andreason
available. A completeHerodot error response looks like this:
{"error": {"code":404,"status":"some-status","request":"foo","reason":"some-reason","details": [{"foo":"bar" }],"message":"foo" }}
To add context to your errors, implementherodot.ErrorContextCarrier
. If youonly want to set the status code of errors implementherodot.StatusCodeCarrier.
About
A lightweight Go library for writing responses and errors to HTTP