-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
47 lines (39 loc) · 871 Bytes
/
response.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
45
46
47
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
func respondWithError(w http.ResponseWriter, code int, res string) {
if code > 499 {
log.Printf("Responding with 5XX error: %s", res)
}
type errresponse struct {
Error string `json:"error"`
}
respondWithJson(w, code, errresponse{
Error: res,
})
}
func respondWithJson(w http.ResponseWriter, code int, res interface{}) {
w.Header().Set("content-type", "application/json")
data, err := json.Marshal(res)
if err != nil {
log.Printf("Error marshalling JSON: %s", err)
w.WriteHeader(500)
return
}
w.WriteHeader(code)
w.Write(data)
}
func writesse(w io.Writer, res interface{}) {
v, err := json.Marshal(res)
if err != nil {
log.Printf("could not marshal response, err:%v", err)
fmt.Fprintf(w, "error: %v\n\n", err)
return
}
fmt.Fprintf(w, "items : %s\n\n", v)
}