Handling Queries over HTTP
To answer a query over HTTP, define a function that receives the request and the user, and returns the query:
toListBooks := func(r *http.Request, user User) (ListBooks, error) {
return ListBooks{
OnlyAvailable: r.URL.Query().Get("available") == "true",
}, nil
}
Then call the Query function with the API, the mux, a pattern, this function, and the function that answers the query:
httpapi.Query(api, mux, "GET /api/books", toListBooks, listBooks(catalog))
The route answers with 200 OK and the result as JSON. Errors are answered as for commands, and errors returned from the first function are treated as they are from ToCommand (see Authorizing Commands).
To answer this way in a handler of your own, call the RespondResult function with the response writer, the result, and the error.
Note that the functions have the types httpapi.ToQuery and httpapi.Answer. The answering function receives neither the request nor the user.
Answering Queries in Your Own Format#
To answer in a format of your own, call the Ask function in a handler of your own. It does the same as a route, but writes nothing to the response. Instead, it returns the result:
mux.HandleFunc("GET /api/books", func(w http.ResponseWriter, r *http.Request) {
books, err := httpapi.Ask(r, api, toListBooks, listBooks(catalog))
if err != nil {
// ...
}
// ...
})
Reporting Missing Items#
If the answering function returns query.ErrNoItems, as query.Single does if no item matches, the request is answered with 404 Not Found:
httpapi.Query(
api,
mux,
"GET /api/books/{id}",
func(r *http.Request, user User) (GetBook, error) {
return GetBook{BookID: r.PathValue("id")}, nil
},
getBook(catalog),
)
To report a missing item yourself, return httpapi.ErrNotFound.