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
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -18,3 +20,17 @@ func NewRouter() *mux.Router {
|
|||||||
|
|
||||||
return v1
|
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
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Health tries to respond that the server is alive.
|
// Health tries to respond that the server is alive.
|
||||||
// If it is not, the response won't reach the client.
|
// If it is not, the response won't reach the client.
|
||||||
func Health(w http.ResponseWriter, r *http.Request) {
|
func Health(writer http.ResponseWriter, _ *http.Request) {
|
||||||
w.WriteHeader(http.StatusOK)
|
writer.WriteHeader(http.StatusOK)
|
||||||
w.Header().Set("Content-Type", "application/json")
|
writeJson(
|
||||||
response, err := json.Marshal(Message{"I'm alive!"})
|
writer,
|
||||||
if err != nil {
|
Message{"I'm alive!"},
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user