Add function to write json to http response writer
This commit is contained in:
16
api/api.go
16
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)
|
||||
}
|
||||
}
|
||||
|
@ -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!"},
|
||||
)
|
||||
}
|
||||
|
Reference in New Issue
Block a user