Senior
How do you develop REST API?
sobes.tech AI
Answer from AI
When developing REST API in Go, I adhere to the following principles:
- Clearly define the structure of resources and their endpoints using understandable URLs.
- Use standard HTTP methods (GET, POST, PUT, DELETE) according to their semantics.
- Serialize data using JSON with the standard encoding/json library.
- Handle errors with clear HTTP statuses and messages.
- Structure code using middleware for logging, authentication, and validation.
- Write tests for each endpoint.
Example of a simple handler:
func getUserHandler(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
user, err := getUserByID(id)
if err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}