Adding HTTP headers to your API
The first thing we can do is add ETags to our APIs. We will change specifically the handleGetList handler and implement the usage of the ETag header. We will use the sha256 hash of the list to generate an ETag. Let’s see how we can do that:
func handleGetList(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
list, err := repository.GetShopingList(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := json.Marshal(list)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
etag := fmt.Sprintf(`"%x"`, sha256.Sum256(data))
if match := r.Header.Get("If-None-Match"); match == etag {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("ETag", etag)
w.Write(data)
return
}
As you can see, adding ETags to our API is very simple. We just need to calculate...