Documentation ¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var (
ErrDecoder = errors.New("json.Decoder error")
)
Functions ¶
func HandleRequest ¶
HandleRequest reads the request body and unmarshals it into a value of type T which is then passed to the supplied function to handle the request. After being read, the request Body is replaced with a new ReadCloser so that it may be re-read by the handler function if required.
if the request body is empty, the handler function is called with a nil value.
if the request body is not empty but cannot be unmarshalled into a value of type T, an error is returned.
if the request body contains fields that are not expected by the handler function, they are ignored and discarded
To automatically treat unexpected fields or an empty body as an error, use the StrictRequest function.
example ¶
func PostResource(rw http.ResponseWriter, rq *http.Request) any { type resource struct { Name string `json:"name"` } return restapi.HandleRequest(rq, func(r *resource) any { if r == nil { return restapi.BadRequest(restapi.ErrBodyRequired) } // if the request includes an "id" field it is ignored r.id = uuid.New().String() // ... create a new resource with the required name ... return restapi.Created().WithValue(r) }) }
func StrictRequest ¶
StrictRequest reads the request body and unmarshals it into a value of type T which is then passed to the supplied function to handle the request. After being read, the request Body is replaced with a new ReadCloser so that it may be re-read by the handler function if required.
The supplied function is not called if:
the request body is not empty but cannot be unmarshalled into a value of type T;
the request body is empty; restapi.BadRequest(restapi.ErrBodyRequired) is returned;
the request body contains fields that are not expected by the marshalled value type; restapi.BadRequest(restapi.ErrUnexpectedField) is returned.
To accept requests with no body or which may contain additional fields not supported by the type parameter T, use HandleRequest.
example ¶
func PostResource(rw http.ResponseWriter, rq *http.Request) any { type resource struct { Name string `json:"name"` } return restapi.StrictRequest(rq, func(r *resource) any { r := struct { ID string `json:"id"` resource }{ ID: uuid.New().String(), resource: resource { Name: r.Name, }, } // ... create the new resource ... return restapi.Created().WithValue(r) }) }
Types ¶
This section is empty.