This repository has been archived by the owner on Dec 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
383 lines (286 loc) · 7.89 KB
/
context.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package golam
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"github.com/aws/aws-lambda-go/events"
"io"
"net"
"net/http"
"net/url"
"strings"
)
const (
defaultIndent = "\t"
)
type Context interface {
Ctx() context.Context
Set(key interface{}, val interface{})
Get(key interface{}) interface{}
SetRequest(r *http.Request)
Request() *http.Request
RequestBody() io.ReadCloser
RequestBodyString() string
RequestBodyBytes() []byte
SetResponse(r *Response)
Response() *Response
Scheme() string
RealIP() string
Path() string
SetPath(p string)
PathParams() PathParams
SetPathParams(pathParams PathParams)
QueryParams() url.Values
SetQueryParams(query url.Values)
Cookie(name string) (*http.Cookie, error)
SetCookie(cookie *http.Cookie)
Cookies() []*http.Cookie
NoContent(status int) error
HTML(status int, html string) error
HTMLBytes(status int, b []byte) error
String(status int, s string) error
JSON(status int, i interface{}) error
JSONPretty(status int, i interface{}) error
JSONWithIndent(status int, i interface{}, indent string) error
JSONBytes(status int, b []byte) error
XML(status int, i interface{}) error
XMLPretty(status int, i interface{}) error
XMLWithIndent(status int, i interface{}, indent string) error
XMLBytes(status int, b []byte) error
ResultStream(status int, contentType string, reader io.Reader) error
Result(status int, contentType string, b []byte) error
Write(b []byte) (int, error)
Redirect(status int, url string) error
// TODO
//Logger() log.Logger
// TODO
//SetLogger(l log.Logger)
Golam() *Golam
PrimalRequest() interface{}
PrimalRequestLambda() *events.APIGatewayV2HTTPRequest
PrimalRequestHTTP() *http.Request
}
var _ Context = (*contextImpl)(nil)
type contextImpl struct {
ctx context.Context
request *http.Request
requestBodyBytes []byte
response *Response
path string
pathParams PathParams
query url.Values
handler HandlerFunc
golam *Golam
primalRequestLambda *events.APIGatewayV2HTTPRequest
primalRequestHTTP *http.Request
// TODO
//logger log.Logger
}
func (c *contextImpl) Ctx() context.Context {
if c.ctx == nil {
c.ctx = c.Request().Context()
}
return c.ctx
}
func (c *contextImpl) Set(key interface{}, val interface{}) {
c.ctx = context.WithValue(c.Ctx(), key, val)
}
func (c *contextImpl) Get(key interface{}) interface{} {
return c.Ctx().Value(key)
}
func (c *contextImpl) writeContentType(value string) {
header := c.Response().Header()
if header.Get(HeaderContentType) == "" {
header.Set(HeaderContentType, value)
}
}
func (c *contextImpl) SetRequest(r *http.Request) {
c.request = r
}
func (c *contextImpl) Request() *http.Request {
return c.request
}
func (c *contextImpl) RequestBody() io.ReadCloser {
return c.Request().Body
}
func (c *contextImpl) RequestBodyString() string {
return string(c.RequestBodyBytes())
}
func (c *contextImpl) RequestBodyBytes() []byte {
if c.requestBodyBytes != nil {
return c.requestBodyBytes
}
var buf bytes.Buffer
tee := io.TeeReader(c.request.Body, &buf)
var err error
c.requestBodyBytes, err = io.ReadAll(tee)
if err != nil {
//TODO: logging
return []byte{}
}
c.request.Body = io.NopCloser(&buf)
return c.requestBodyBytes
}
func (c *contextImpl) SetResponse(r *Response) {
c.response = r
}
func (c *contextImpl) Response() *Response {
return c.response
}
func (c *contextImpl) Scheme() string {
return getSchemeFromHeader(c.request.Header)
}
func (c *contextImpl) RealIP() string {
header := c.request.Header
if ip := header.Get(HeaderXForwardedFor); ip != "" {
i := strings.IndexAny(ip, ",")
if i > 0 {
return strings.TrimSpace(ip[:i])
}
return ip
}
if ip := header.Get(HeaderXRealIP); ip != "" {
return ip
}
ra, _, _ := net.SplitHostPort(c.request.RemoteAddr)
return ra
}
func (c *contextImpl) Path() string {
return c.path
}
func (c *contextImpl) SetPath(p string) {
c.path = p
}
func (c *contextImpl) PathParams() PathParams {
return c.pathParams
}
func (c *contextImpl) SetPathParams(pathParams PathParams) {
c.pathParams = pathParams
}
func (c *contextImpl) QueryParams() url.Values {
return c.query
}
func (c *contextImpl) SetQueryParams(query url.Values) {
c.query = query
}
func (c *contextImpl) Cookie(name string) (*http.Cookie, error) {
return c.Request().Cookie(name)
}
func (c *contextImpl) SetCookie(cookie *http.Cookie) {
c.Response().SetCookie(cookie)
}
func (c *contextImpl) Cookies() []*http.Cookie {
return c.Request().Cookies()
}
func (c *contextImpl) NoContent(status int) error {
c.Response().WriteHeader(status)
return nil
}
func (c *contextImpl) HTML(status int, html string) error {
return c.HTMLBytes(status, []byte(html))
}
func (c *contextImpl) HTMLBytes(status int, b []byte) error {
return c.Result(status, MIMETextHTMLCharsetUTF8, b)
}
func (c *contextImpl) String(status int, s string) error {
return c.Result(status, MIMETextPlainCharsetUTF8, []byte(s))
}
func (c *contextImpl) json(status int, i interface{}, indent string) error {
c.writeContentType(MIMEApplicationJSONCharsetUTF8)
c.Response().WriteHeader(status)
enc := json.NewEncoder(c)
if indent != "" {
enc.SetIndent("", indent)
}
return enc.Encode(i)
}
func (c *contextImpl) JSON(status int, i interface{}) error {
// TODO
// indent := ""
// if debugOn {
// indent = defaultIndent
// }
return c.json(status, i, "")
}
func (c *contextImpl) JSONPretty(status int, i interface{}) error {
return c.JSONWithIndent(status, i, defaultIndent)
}
func (c *contextImpl) JSONWithIndent(status int, i interface{}, indent string) error {
return c.json(status, i, indent)
}
func (c *contextImpl) JSONBytes(status int, b []byte) (err error) {
return c.Result(status, MIMEApplicationJSONCharsetUTF8, b)
}
func (c *contextImpl) xml(status int, i interface{}, indent string) (err error) {
c.writeContentType(MIMEApplicationXMLCharsetUTF8)
c.Response().WriteHeader(status)
enc := xml.NewEncoder(c)
if indent != "" {
enc.Indent("", indent)
}
if _, err = c.Write([]byte(xml.Header)); err != nil {
return
}
return enc.Encode(i)
}
func (c *contextImpl) XML(status int, i interface{}) error {
// TODO
// indent := ""
// if debugOn {
// indent = defaultIndent
// }
return c.xml(status, i, "")
}
func (c *contextImpl) XMLPretty(status int, i interface{}) error {
return c.XMLWithIndent(status, i, defaultIndent)
}
func (c *contextImpl) XMLWithIndent(status int, i interface{}, indent string) error {
return c.xml(status, i, indent)
}
func (c *contextImpl) XMLBytes(status int, b []byte) (err error) {
c.writeContentType(MIMEApplicationXMLCharsetUTF8)
c.Response().WriteHeader(status)
if _, err = c.Write([]byte(xml.Header)); err != nil {
return
}
_, err = c.Write(b)
return
}
func (c *contextImpl) ResultStream(status int, contentType string, reader io.Reader) (err error) {
c.writeContentType(contentType)
c.Response().WriteHeader(status)
_, err = io.Copy(c.Response(), reader)
return
}
func (c *contextImpl) Result(status int, contentType string, b []byte) (err error) {
return c.ResultStream(status, contentType, bytes.NewReader(b))
}
func (c *contextImpl) Write(b []byte) (int, error) {
return c.Response().Write(b)
}
func (c *contextImpl) Redirect(status int, url string) error {
if status < http.StatusMultipleChoices ||
status > http.StatusPermanentRedirect {
return errors.New("invalid redirect status code")
}
c.Response().Header().Set(HeaderLocation, url)
c.Response().WriteHeader(status)
return nil
}
func (c *contextImpl) Golam() *Golam {
return c.golam
}
func (c *contextImpl) PrimalRequest() interface{} {
if isLambdaRuntime() {
return c.PrimalRequestLambda()
}
return c.PrimalRequestHTTP()
}
func (c *contextImpl) PrimalRequestLambda() *events.APIGatewayV2HTTPRequest {
return c.primalRequestLambda
}
func (c *contextImpl) PrimalRequestHTTP() *http.Request {
return c.primalRequestHTTP
}