I am learning about the best practices involved in REST API design and wrote a function which handles the GET /cities HTTP/1.1 query.
This function contains cities which is a struct array that holds the cityname, citycode of multiple cities.
Below is the code
func FindCitiesHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
if len(cities) == 0 {
w.WriteHeader(404)
return
}
if err := json.NewEncoder(w).Encode(cities); err != nil {
/* what to do here? */
}
w.WriteHeader(200)
}
Now when I started thinking about the possible outcomes of this function. I found these situations.
It returns all the cities properly as JSON response successfully. So I return 200 http status.
The list of cities is empty. So there is nothing to return. So I return 404 (resource not found)
It is about to return JSON response of all cities, but something gone wrong during JSON encoding. Now I am confused here, how do I deal with this situation.
I mean how do you convey message properly to user, if
- If your business/application logic had some error/exception.
- If data access logic found some issues. (say connection to database is not reachable)
Could you guys please help me to suggest best practices you followed in these situations?