/
http.go
122 lines (105 loc) · 3.08 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package api
import (
"bytes"
"encoding/json"
"math/rand"
"net/http"
"time"
"github.com/stefanprodan/k8s-podinfo/pkg/version"
"go.uber.org/zap"
)
func randomDelayMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
min := 0
max := 5
rand.Seed(time.Now().Unix())
delay := rand.Intn(max-min) + min
time.Sleep(time.Duration(delay) * time.Second)
next.ServeHTTP(w, r)
})
}
func randomErrorMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rand.Seed(time.Now().Unix())
if rand.Int31n(3) == 0 {
errors := []int{http.StatusInternalServerError, http.StatusBadRequest, http.StatusConflict}
w.WriteHeader(errors[rand.Intn(len(errors))])
return
}
next.ServeHTTP(w, r)
})
}
func versionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("X-API-Version", version.VERSION)
r.Header.Set("X-API-Revision", version.REVISION)
next.ServeHTTP(w, r)
})
}
// TODO: use Istio tracing package
// https://github.com/istio/istio/blob/master/pkg/tracing/config.go
func copyTracingHeaders(from *http.Request, to *http.Request) {
headers := []string{
"x-request-id",
"x-b3-traceid",
"x-b3-spanid",
"x-b3-parentspanid",
"x-b3-sampled",
"x-b3-flags",
"x-ot-span-context",
}
for i := range headers {
headerValue := from.Header.Get(headers[i])
if len(headerValue) > 0 {
to.Header.Set(headers[i], headerValue)
}
}
}
func (s *Server) JSONResponse(w http.ResponseWriter, r *http.Request, result interface{}) {
body, err := json.Marshal(result)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
s.logger.Error("JSON marshal failed", zap.Error(err))
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
w.Write(prettyJSON(body))
}
func (s *Server) JSONResponseCode(w http.ResponseWriter, r *http.Request, result interface{}, responseCode int) {
body, err := json.Marshal(result)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
s.logger.Error("JSON marshal failed", zap.Error(err))
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(responseCode)
w.Write(prettyJSON(body))
}
func (s *Server) ErrorResponse(w http.ResponseWriter, r *http.Request, error string, code int) {
data := struct {
Code int `json:"code"`
Message string `json:"message"`
}{
Code: code,
Message: error,
}
body, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
s.logger.Error("JSON marshal failed", zap.Error(err))
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
w.Write(prettyJSON(body))
}
func prettyJSON(b []byte) []byte {
var out bytes.Buffer
json.Indent(&out, b, "", " ")
return out.Bytes()
}