mirror of
https://github.com/documize/community.git
synced 2025-07-20 05:39:42 +02:00
WriteJSON method
This commit is contained in:
parent
56fe047136
commit
170c20c8bc
1 changed files with 25 additions and 0 deletions
|
@ -12,6 +12,7 @@
|
|||
package util
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
|
@ -124,3 +125,27 @@ func WriteSuccessEmptyJSON(w http.ResponseWriter) {
|
|||
_, err := w.Write([]byte("{}"))
|
||||
log.IfErr(err)
|
||||
}
|
||||
|
||||
func WriteMarshalError(w http.ResponseWriter, err error) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, err2 := w.Write([]byte("{Error: 'JSON marshal failed'}"))
|
||||
log.IfErr(err2)
|
||||
log.Error("Failed to JSON marshal", err)
|
||||
}
|
||||
|
||||
// WriteJSON serializes data as JSON to HTTP response.
|
||||
func WriteJSON(w http.ResponseWriter, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
j, err := json.Marshal(v)
|
||||
|
||||
if err != nil {
|
||||
WriteMarshalError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = w.Write(j)
|
||||
log.IfErr(err)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue