-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
83 lines (69 loc) · 1.82 KB
/
http.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package utils
import (
"encoding/json"
"fmt"
"net/http"
"runtime/debug"
"strconv"
"strings"
"github.com/rl404/shimakaze/internal/errors"
)
// Response is standard api response model.
type Response struct {
Status int `json:"status"`
Message string `json:"message"`
Data interface{} `json:"data" swaggertype:"object"`
Meta interface{} `json:"meta" swaggertype:"object"`
}
// ResponseWithJSON to write response with JSON format.
func ResponseWithJSON(w http.ResponseWriter, code int, data interface{}, err error, meta ...interface{}) {
r := Response{
Status: code,
Message: strings.ToLower(http.StatusText(code)),
}
if len(meta) > 0 && meta[0] != nil {
r.Meta = meta[0]
}
r.Data = data
if err != nil {
r.Message = err.Error()
}
rJSON, _ := json.Marshal(r)
// Set response header.
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(rJSON)))
w.WriteHeader(code)
_, _ = w.Write(rJSON)
}
// ResponseWithPNG to write response with PNG.
func ResponseWithPNG(w http.ResponseWriter, code int, data []byte, err error) {
if err != nil {
ResponseWithJSON(w, code, nil, err)
return
}
// Set response header.
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.WriteHeader(code)
_, _ = w.Write(data)
}
// Recoverer is custom recoverer middleware.
// Will return 500.
func Recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil {
ResponseWithJSON(
w,
http.StatusInternalServerError,
nil,
errors.Wrap(
r.Context(),
errors.ErrInternalServer,
fmt.Errorf("%v", rvr),
fmt.Errorf("%s", debug.Stack())))
}
}()
next.ServeHTTP(w, r)
})
}