Responding
A big part of any API is responding to requests with a combination of status codes, data, errors, and sometimes headers – the net/http
package makes all of this very easy to do. One option we have, which remains the best option for tiny projects or even the early stages of big projects, is to just build the response code directly inside the handler.
As the number of handlers grows, however, we will end up duplicating a lot of code and sprinkling representation decisions all over our project. A more scalable approach is to abstract the response code into helper functions.
For the first version of our API, we are going to speak only JSON, but we want the flexibility to add other representations later if we need to.
Create a new file called respond.go
and add the following code:
func decodeBody(r *http.Request, v interface{}) error { defer r.Body.Close() return json.NewDecoder(r.Body).Decode(v) } func encodeBody(w http.ResponseWriter, r *http.Request, v interface{}) error {...