-
Notifications
You must be signed in to change notification settings - Fork 5
/
json_writer.go
40 lines (35 loc) · 1.02 KB
/
json_writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package common
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
)
type JsonResponse struct {
Error string `json:"error"`
Success bool `json:"success"`
Payload interface{} `json:"payload"`
}
type JsonWriter struct {
HttpWriter
}
func NewJsonWriter() *JsonWriter {
return &JsonWriter{}
}
func (writer *JsonWriter) Write(w http.ResponseWriter, status int, response interface{}) {
jsonResponse, err := json.Marshal(response)
if err != nil {
errResponse := JsonResponse{Error: fmt.Sprintf("JsonWriter failed to marshal response entity %s %+v", reflect.TypeOf(response), response)}
errBytes, err := json.Marshal(errResponse)
if err != nil {
errResponse := JsonResponse{Error: "JsonWriter internal server error"}
errBytes, _ := json.Marshal(errResponse)
http.Error(w, string(errBytes), http.StatusInternalServerError)
}
http.Error(w, string(errBytes), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonResponse)
}