-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
44 lines (36 loc) · 788 Bytes
/
json.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
41
42
43
44
package main
import (
"encoding/json"
"log"
"net/http"
"os"
)
func responseWithError(w http.ResponseWriter, code int, msg string) {
if code > 499 {
log.Println("Responding with 5xx error:", msg)
}
type errorResponse struct {
Error string `json:"error"`
}
responseWithJson(w, code, errorResponse{
Error: msg,
})
}
func responseWithJson(w http.ResponseWriter, code int, payload interface{}) {
appName := os.Getenv("APP_NAME")
dat, err := json.Marshal(struct {
App string `json:"app"`
Data interface{} `json:"data"`
}{
App: appName,
Data: payload,
})
if err != nil {
log.Printf("Fail to marshal json response %v", payload)
w.WriteHeader(500)
return
}
w.Header().Add("content-type", "application/json")
w.WriteHeader(code)
w.Write(dat)
}