diff --git a/api/api.go b/api/api.go index 8153a6c..7853e86 100644 --- a/api/api.go +++ b/api/api.go @@ -1,7 +1,9 @@ package api import ( + "encoding/json" "github.com/gorilla/mux" + "log" "net/http" ) @@ -18,3 +20,17 @@ func NewRouter() *mux.Router { return v1 } + +func writeJson(writer http.ResponseWriter, content interface{}) { + writer.Header().Set("Content-Type", "application/json") + response, err := json.Marshal(content) + if err != nil { + log.Printf("JSON marshal error: %v\n", err) + http.Error(writer, err.Error(), http.StatusInternalServerError) + return + } + if _, err := writer.Write(response); err != nil { + log.Printf("Error writing JSON to response: %v\n", err) + http.Error(writer, err.Error(), http.StatusInternalServerError) + } +} diff --git a/api/health.go b/api/health.go index 0a403df..2efae3c 100644 --- a/api/health.go +++ b/api/health.go @@ -1,23 +1,15 @@ package api import ( - "encoding/json" - "log" "net/http" ) // Health tries to respond that the server is alive. // If it is not, the response won't reach the client. -func Health(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - response, err := json.Marshal(Message{"I'm alive!"}) - if err != nil { - log.Printf("JSON marshal error in health route: %v\n", err) - http.Error(w, err.Error(), http.StatusInternalServerError) - } - if _, err := w.Write(response); err != nil { - log.Printf("Error handling the health route: %v\n", err) - http.Error(w, err.Error(), http.StatusInternalServerError) - } +func Health(writer http.ResponseWriter, _ *http.Request) { + writer.WriteHeader(http.StatusOK) + writeJson( + writer, + Message{"I'm alive!"}, + ) }