Package httpapi
provides support for implementing HTTP servers that expose a JSON API.
Example of a handler that extracts the input from the body of the HTTP request.
func postHandler(w http.ResponseWriter, r *http.Request) {
// unmarshal input from request
var input DoSomethingInput
if err := httpapi.ReadRequest(w, r, &input); err != nil {
httpapi.WriteError(w, r, err)
return
}
output, err := doSomethingWith(r.Context(), &input)
if err != nil {
httpapi.WriteError(w, r, err)
return
}
httpapi.WriteResponse(w, r, output)
}
Example of a handler that extracts the input from the query strings of the HTTP request.
func getHandler(w http.ResponseWriter, r *http.Request) {
query := httpapi.Query(r)
input := DoAnotherThingInput {
Since: query.GetTime("since"),
Limit: query.GetInt("limit"),
Offset: query.GetInt("offset"),
}
// validate once after all query string parameters have been read
if err := query.Err(); err != nil {
httpapi.WriteResponse(w, r, err)
return
}
output, err := doAnotherThingWith(r.Context(), &input)
if err != nil {
httpapi.WriteError(w, r, err)
return
}
httpapi.WriteResponse(w, r, output)
}