-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
294 lines (249 loc) · 7.61 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
package kid
import (
"context"
"net/http"
"net/url"
"sync"
)
const contentTypeHeader string = "Content-Type"
// Context is the context of current HTTP request.
// It holds data related to current HTTP request.
type Context struct {
request *http.Request
response ResponseWriter
params Params
storage Map
kid *Kid
lock sync.Mutex
routeName string
}
// newContext returns a new empty context.
func newContext(k *Kid) *Context {
c := Context{kid: k}
return &c
}
// reset resets the context.
func (c *Context) reset(request *http.Request, response http.ResponseWriter) {
c.request = request
c.response = newResponse(response)
c.storage = make(Map)
c.params = make(Params)
c.routeName = ""
}
// setParams sets request's path parameters.
func (c *Context) setParams(params Params) {
c.params = params
}
// setRouteName sets the route name.
func (c *Context) setRouteName(name string) {
c.routeName = name
}
// Request returns plain request of current HTTP request.
func (c *Context) Request() *http.Request {
return c.request
}
// Response returns plain response of current HTTP request.
func (c *Context) Response() ResponseWriter {
return c.response
}
// Param returns path parameter's value.
func (c *Context) Param(name string) string {
return c.params[name]
}
// Params returns all of the path parameters.
func (c *Context) Params() Params {
return c.params
}
// Path returns request's path used for matching request to a handler.
func (c *Context) Path() string {
u := c.request.URL
if u.RawPath != "" {
return u.RawPath
}
return u.Path
}
// Route returns current request's route name.
// It's the user entered path, e.g. /greet/{name}.
func (c *Context) Route() string {
return c.routeName
}
// Method returns request method.
func (c *Context) Method() string {
return c.request.Method
}
// QueryParam returns value of a query parameter
func (c *Context) QueryParam(name string) string {
queryParam := c.request.URL.Query().Get(name)
return queryParam
}
// QueryParamMultiple returns multiple values of a query parameter.
//
// Useful when query parameters are like ?name=x&name=y.
func (c *Context) QueryParamMultiple(name string) []string {
params := c.request.URL.Query()[name]
if params == nil {
return []string{}
}
return params
}
// QueryParams returns all of the query parameters.
func (c *Context) QueryParams() url.Values {
return c.request.URL.Query()
}
// mustWrite writes raw bytes to the response.
func (c *Context) mustWrite(blob []byte) {
if _, err := c.Response().Write(blob); err != nil {
panic(err)
}
}
// JSON sends JSON response with the given status code.
func (c *Context) JSON(code int, obj any) {
c.writeContentType("application/json")
c.response.WriteHeader(code)
c.kid.jsonSerializer.Write(c.Response(), obj, "")
}
// JSONIndent sends JSON response with the given status code.
// Sends response with the given indent.
func (c *Context) JSONIndent(code int, obj any, indent string) {
c.writeContentType("application/json")
c.response.WriteHeader(code)
c.kid.jsonSerializer.Write(c.Response(), obj, indent)
}
// JSONByte sends JSON response with the given status code.
// Writes JSON blob untouched to response.
func (c *Context) JSONByte(code int, blob []byte) {
c.writeContentType("application/json")
c.response.WriteHeader(code)
c.mustWrite(blob)
}
// ReadJSON reads request's body as JSON and stores it in the given object.
// The object must be a pointer.
func (c *Context) ReadJSON(out any) error {
return c.kid.jsonSerializer.Read(c.Request(), out)
}
// XML sends XML response with the given status code.
//
// Returns an error if an error happened during sending response otherwise returns nil.
func (c *Context) XML(code int, obj any) {
c.writeContentType("application/xml")
c.response.WriteHeader(code)
c.kid.xmlSerializer.Write(c.Response(), obj, "")
}
// XMLIndent sends XML response with the given status code.
// Sends response with the given indent.
func (c *Context) XMLIndent(code int, obj any, indent string) {
c.writeContentType("application/xml")
c.response.WriteHeader(code)
c.kid.xmlSerializer.Write(c.Response(), obj, indent)
}
// XMLByte sends XML response with the given status code.
// Writes JSON blob untouched to response.
func (c *Context) XMLByte(code int, blob []byte) {
c.writeContentType("application/xml")
c.response.WriteHeader(code)
c.mustWrite(blob)
}
// ReadXML reads request's body as XML and stores it in the given object.
// The object must be a pointer.
func (c *Context) ReadXML(out any) error {
return c.kid.xmlSerializer.Read(c.Request(), out)
}
// HTML sends HTML response with the given status code.
//
// tpl must be a relative path to templates root directory.
// Defaults to "templates/".
func (c *Context) HTML(code int, tpl string, data any) {
c.writeContentType("text/html")
c.response.WriteHeader(code)
c.kid.htmlRenderer.RenderHTML(c.Response(), tpl, data)
}
// HTMLString sends bare string as HTML response with the given status code.
func (c *Context) HTMLString(code int, tpl string) {
c.writeContentType("text/html")
c.response.WriteHeader(code)
c.mustWrite([]byte(tpl))
}
// String sends bare string as a plain text response with the given status code.
func (c *Context) String(code int, data string) {
c.writeContentType("text/plain")
c.response.WriteHeader(code)
c.mustWrite([]byte(data))
}
// Byte sends bare bytes as response with the given status code.
func (c *Context) Byte(code int, data []byte) {
c.writeContentType("application/octet-stream")
c.response.WriteHeader(code)
c.mustWrite([]byte(data))
}
// NoContent returns an empty response with the given status code.
func (c *Context) NoContent(code int) {
c.response.WriteHeader(code)
c.response.WriteHeaderNow()
}
// GetResponseHeader gets a response header.
func (c *Context) GetResponseHeader(key string) string {
return c.response.Header().Get(key)
}
// SetResponseHeader sets a header to the response.
func (c *Context) SetResponseHeader(key, value string) {
c.response.Header().Set(key, value)
}
// SetRequestHeader sets a header to the request.
func (c *Context) SetRequestHeader(key, value string) {
c.request.Header.Set(key, value)
}
// GetRequestHeader gets a request header.
func (c *Context) GetRequestHeader(key string) string {
return c.request.Header.Get(key)
}
// writeContentType sets content type header for response.
// It won't overwrite content type if it's already set.
func (c *Context) writeContentType(contentType string) {
if c.GetResponseHeader(contentTypeHeader) == "" {
c.SetResponseHeader(contentTypeHeader, contentType)
}
}
// Set sets a key-value pair to current request's context.
func (c *Context) Set(key string, val any) {
c.lock.Lock()
defer c.lock.Unlock()
c.storage[key] = val
}
// Get gets a value from current request's context.
func (c *Context) Get(key string) (any, bool) {
c.lock.Lock()
defer c.lock.Unlock()
val, ok := c.storage[key]
return val, ok
}
// Clone clones the context and returns it.
//
// Should be used when context is passed to the background jobs.
//
// Writes to the response of a cloned context will panic.
func (c *Context) Clone() *Context {
ctx := Context{
request: c.request.Clone(context.Background()),
response: c.response.(*response).clone(),
kid: c.kid,
lock: sync.Mutex{},
routeName: c.routeName,
}
// Copy path params.
params := make(Params, len(c.params))
for k, v := range c.params {
params[k] = v
}
ctx.params = params
// Copy storage.
storage := make(Map, len(c.storage))
for k, v := range c.storage {
storage[k] = v
}
ctx.storage = storage
return &ctx
}
// Debug returns whether we are in debug mode or not.
func (c *Context) Debug() bool {
return c.kid.Debug()
}