-
Notifications
You must be signed in to change notification settings - Fork 5
/
responses.go
52 lines (42 loc) · 1.17 KB
/
responses.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
48
49
50
51
52
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
)
type ResponseHandler func(*http.Request) http.Handler
func (f ResponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f(r).ServeHTTP(w, r)
}
type JsonResponseHandler struct {
Body interface{}
StatusCode int
}
func (jr JsonResponseHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
content, err := json.MarshalIndent(jr.Body, "", "\t")
if err != nil {
log.Println("JSON response marshalling error:", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Content-Length", strconv.Itoa(len(content)))
w.WriteHeader(jr.StatusCode)
w.Write(content)
}
func JsonResponseOk(body interface{}) JsonResponseHandler {
return JsonResponseHandler{body, http.StatusOK}
}
func JsonResponseCreated(body interface{}) JsonResponseHandler {
return JsonResponseHandler{body, http.StatusCreated}
}
func ErrorResponse(message string, status int) http.Handler {
return JsonResponseHandler{
Body: map[string]string{
"status": "error",
"message": message,
},
StatusCode: status,
}
}