-
Notifications
You must be signed in to change notification settings - Fork 1
/
writer.go
245 lines (207 loc) · 6.07 KB
/
writer.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright 2021 Teal.Finance/Garcon contributors
// This file is part of Teal.Finance/Garcon,
// an API and website server under the MIT License.
// SPDX-License-Identifier: MIT
package garcon
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/teal-finance/garcon/gg"
)
const (
pathReserved = "Path is reserved for future use. Please contact us to share your ideas."
pathInvalid = "Path is not valid. Please refer to the documentation."
)
// Writer enables writing useful JSON error message in the HTTP response body.
type Writer string
// NewWriter creates a Writer structure.
func NewWriter(docURL string) Writer {
return Writer(docURL)
}
func NotImplemented(w http.ResponseWriter, r *http.Request) {
Writer("").NotImplemented(w, r)
}
func InvalidPath(w http.ResponseWriter, r *http.Request) {
Writer("").InvalidPath(w, r)
}
func (gw Writer) NotImplemented(w http.ResponseWriter, r *http.Request) {
gw.WriteErr(w, r, http.StatusNotImplemented, pathReserved)
}
func (gw Writer) InvalidPath(w http.ResponseWriter, r *http.Request) {
gw.WriteErr(w, r, http.StatusBadRequest, pathInvalid)
}
func WriteErr(w http.ResponseWriter, r *http.Request, statusCode int, kv ...any) {
Writer("").WriteErr(w, r, statusCode, kv...)
}
func WriteOK(w http.ResponseWriter, kv ...any) {
Writer("").WriteOK(w, kv...)
}
// TraversalPath returns true when path contains ".." to prevent path traversal attack.
func (gw Writer) TraversalPath(w http.ResponseWriter, r *http.Request) bool {
if strings.Contains(r.URL.Path, "..") {
gw.WriteErr(w, r, http.StatusBadRequest, "URL contains '..'")
log.Warn("reject path with '..'", gg.Sanitize(r.URL.Path))
return true
}
return false
}
// WriteErr is a fast pretty-JSON marshaler dedicated to the HTTP error response.
// WriteErr extends the JSON content when more than two key-values (kv) are provided.
func (gw Writer) WriteErr(w http.ResponseWriter, r *http.Request, statusCode int, kv ...any) {
buf := make([]byte, 0, 1024)
buf = append(buf, '{')
buf, comma := appendMessages(buf, kv)
if r != nil {
if comma {
buf = append(buf, ',', '\n')
}
buf = appendURL(buf, r.URL)
comma = true
}
if string(gw) != "" {
if comma {
buf = append(buf, ',', '\n')
}
buf = gw.appendDoc(buf)
}
buf = append(buf, '}')
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
w.Write(buf)
}
// WriteOK is a fast pretty-JSON marshaler dedicated to the HTTP successful response.
func (gw Writer) WriteOK(w http.ResponseWriter, kv ...any) {
var buf []byte
var err error
switch {
case len(kv) == 0:
buf = []byte("{}")
case len(kv) == 1:
buf, err = json.Marshal(kv[0])
if err != nil {
gw.WriteErr(w, nil, http.StatusInternalServerError,
"Cannot serialize success JSON response", "error", err)
return
}
default:
buf = make([]byte, 0, 1024) // 1024 = max bytes of most of the JSON responses
buf = append(buf, '{')
buf = appendKeyValues(buf, false, kv)
buf = append(buf, '}')
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(buf)
}
func appendMessages(buf []byte, kv []any) (_ []byte, comma bool) {
if len(kv) == 0 {
return buf, false
}
// {"message":"xxxxx"} is more common than {"error":"xxxxx"}
buf = append(buf, []byte(`"message":`)...)
if len(kv) == 2 {
s := fmt.Sprintf("%v%v", kv[0], kv[1])
buf = strconv.AppendQuoteToGraphic(buf, s)
return buf, true
}
buf = appendValue(buf, kv[0])
if len(kv) > 1 {
buf = appendKeyValues(buf, true, kv[1:])
}
return buf, true
}
func appendKeyValues(buf []byte, comma bool, kv []any) []byte {
if (len(kv) == 0) || (len(kv)%2 != 0) {
log.Panic("Writer: want non-zero even len(kv) but got", len(kv))
}
for i := 0; i < len(kv); i += 2 {
if comma {
buf = append(buf, ',', '\n')
} else {
comma = true
}
buf = appendKey(buf, kv[i])
buf = append(buf, ':')
buf = appendValue(buf, kv[i+1])
}
return buf
}
//nolint:cyclop,gocyclo // cannot reduce cyclomatic complexity
func appendValue(buf []byte, a any) []byte {
switch val := a.(type) {
case bool:
return strconv.AppendBool(buf, val)
case float32:
return strconv.AppendFloat(buf, float64(val), 'f', 9, 32)
case float64:
return strconv.AppendFloat(buf, val, 'f', 9, 64)
case int:
return strconv.AppendInt(buf, int64(val), 10)
case int8:
return strconv.AppendInt(buf, int64(val), 10)
case int16:
return strconv.AppendInt(buf, int64(val), 10)
case int32:
return strconv.AppendInt(buf, int64(val), 10)
case int64:
return strconv.AppendInt(buf, val, 10)
case uint:
return strconv.AppendUint(buf, uint64(val), 10)
case uint8:
return strconv.AppendUint(buf, uint64(val), 10)
case uint16:
return strconv.AppendUint(buf, uint64(val), 10)
case uint32:
return strconv.AppendUint(buf, uint64(val), 10)
case uint64:
return strconv.AppendUint(buf, val, 10)
case uintptr:
return strconv.AppendUint(buf, uint64(val), 10)
case string:
return strconv.AppendQuoteToGraphic(buf, val)
case []byte:
return strconv.AppendQuoteToGraphic(buf, string(val))
case complex64, complex128:
return strconv.AppendQuoteToGraphic(buf, fmt.Sprint(val))
case error:
return strconv.AppendQuoteToGraphic(buf, val.Error())
default:
return appendJSON(buf, val)
}
}
func appendJSON(buf []byte, obj any) []byte {
b, err := json.Marshal(obj)
if err != nil {
log.Errorf("Writer jsonify %+v %v", obj, err)
}
return append(buf, b...)
}
func appendKey(buf []byte, key any) []byte {
switch k := key.(type) {
case string:
return strconv.AppendQuoteToGraphic(buf, k)
case []byte:
return strconv.AppendQuoteToGraphic(buf, string(k))
default:
return strconv.AppendQuoteToGraphic(buf, fmt.Sprint(k))
}
}
func appendURL(buf []byte, u *url.URL) []byte {
buf = append(buf, []byte(`"path":`)...)
buf = strconv.AppendQuote(buf, u.Path)
if u.RawQuery != "" {
buf = append(buf, []byte(",\n"+`"query":`)...)
buf = strconv.AppendQuote(buf, u.RawQuery)
}
return buf
}
func (gw Writer) appendDoc(buf []byte) []byte {
buf = append(buf, '"', 'd', 'o', 'c', '"', ':', '"')
buf = append(buf, []byte(string(gw))...)
buf = append(buf, '"')
return buf
}