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