Add function to write json to http response writer

This commit is contained in:
Felix Auringer
2021-04-27 09:14:08 +02:00
parent 712d0e6420
commit 40aff301d8
2 changed files with 22 additions and 14 deletions

View File

@ -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)
}
}

View File

@ -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!"},
)
}