-
Notifications
You must be signed in to change notification settings - Fork 13
/
context.go
418 lines (335 loc) · 9.35 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package gogo
import (
"crypto"
"math"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/dolab/gogo/internal/params"
"github.com/dolab/gogo/internal/render"
"github.com/dolab/gogo/pkgs/hooks"
)
var (
contextPool = sync.Pool{
New: func() interface{} {
return NewContext()
},
}
// contextNew returns a new context for the request
contextNew = func(w http.ResponseWriter, r *http.Request, ps *params.Params, pkg, ctrl, action string) *Context {
ctx := contextPool.Get().(*Context)
ctx.Response.Hijack(w)
ctx.Request = r
ctx.Params = ps
ctx.Logger = NewRequestLogger(r)
ctx.pkg = pkg
ctx.ctrl = ctrl
ctx.action = action
return ctx
}
// contextReuse puts the context back to pool for later usage
contextReuse = func(ctx *Context) {
contextPool.Put(ctx)
}
)
// Context defines context of a request for gogo.
type Context struct {
Response Responser
Request *http.Request
Params *params.Params
Logger Logger
mux sync.RWMutex
settings map[string]interface{}
frozenSettings map[string]interface{}
cursor int8
pkg string
ctrl string
action string
filters []Middleware
responseReady *hooks.HookList
issuedAt time.Time
}
// NewContext returns a *Context without initialization
func NewContext() *Context {
return &Context{
Response: NewResponse(nil),
cursor: -1,
}
}
// Package returns package path of routed request.
func (c *Context) Package() string {
return c.pkg
}
// Controller returns controller name of routed request.
func (c *Context) Controller() string {
return c.ctrl
}
// Action returns action name of routed request.
func (c *Context) Action() string {
return c.action
}
// ContentType returns first value of request Content-Type header separated by semicolon
func (c *Context) ContentType() string {
s := c.Header("Content-Type")
i := strings.Index(s, ";")
if i == -1 {
i = len(s)
}
return strings.TrimSpace(strings.ToLower(s[:i]))
}
// Set binds a new value with key for the context
func (c *Context) Set(key string, value interface{}) {
if c.settings == nil {
c.settings = make(map[string]interface{})
}
c.settings[key] = value
}
// Get returns a value of the key
func (c *Context) Get(key string) (v interface{}, ok bool) {
if c.settings == nil {
return
}
v, ok = c.settings[key]
return
}
// MustGet returns a value of key or panic when key doesn't exist
func (c *Context) MustGet(key string) interface{} {
v, ok := c.Get(key)
if !ok {
c.Logger.Panicf("Key %s doesn't exist", key)
}
return v
}
// SetFinal binds a value with key for the context and freezes it
func (c *Context) SetFinal(key string, value interface{}) error {
if c.frozenSettings == nil {
c.frozenSettings = make(map[string]interface{})
}
if _, ok := c.frozenSettings[key]; ok {
return ErrSettingsKey
}
c.frozenSettings[key] = value
return nil
}
// GetFinal returns a frozen value of the key
func (c *Context) GetFinal(key string) (v interface{}, ok bool) {
if c.frozenSettings == nil {
return
}
v, ok = c.frozenSettings[key]
return
}
// MustSetFinal likes SetFinal, but it panics if key is duplicated.
func (c *Context) MustSetFinal(key string, value interface{}) {
err := c.SetFinal(key, value)
if err != nil {
c.Logger.Panicf("Freeze key %s duplicated!", key)
}
}
// MustGetFinal returns a frozen value of key or panic when it doesn't exist
func (c *Context) MustGetFinal(key string) interface{} {
v, ok := c.GetFinal(key)
if !ok {
c.Logger.Panicf("Freeze key %s doesn't exist", key)
}
return v
}
// RequestID returns request id of the Context
func (c *Context) RequestID() string {
if c.Logger == nil {
return ""
}
return c.Logger.RequestID()
}
// RequestURI returns request raw uri of http.Request
func (c *Context) RequestURI() string {
if c.Request.RequestURI != "" {
return c.Request.RequestURI
}
uri, _ := url.QueryUnescape(c.Request.URL.EscapedPath())
return uri
}
// HasRawHeader returns true if request sets its header with specified key
func (c *Context) HasRawHeader(key string) bool {
for yek := range c.Request.Header {
if key == yek {
return true
}
}
return false
}
// RawHeader returns raw request header value of specified key
func (c *Context) RawHeader(key string) []string {
for yek, vals := range c.Request.Header {
if key == yek {
return vals
}
}
return nil
}
// HasHeader returns true if request sets its header for canonicaled specified key
func (c *Context) HasHeader(key string) bool {
_, ok := c.Request.Header[http.CanonicalHeaderKey(key)]
return ok
}
// Header returns request header value of canonicaled specified key
func (c *Context) Header(key string) string {
return c.Request.Header.Get(key)
}
// SetStatus sets response status code
func (c *Context) SetStatus(code int) {
c.Response.WriteHeader(code)
}
// AddHeader adds response header with key/value pair
func (c *Context) AddHeader(key, value string) {
c.Response.Header().Add(key, value)
}
// SetHeader sets response header with key/value pair
func (c *Context) SetHeader(key, value string) {
c.Response.Header().Set(key, value)
}
// Redirect returns a HTTP redirect to the specific location.
func (c *Context) Redirect(location string) {
// always abort
c.Abort()
// adjust status code, default to 302
status := c.Response.Status()
switch status {
case http.StatusMovedPermanently, http.StatusSeeOther, http.StatusTemporaryRedirect:
// skip
default:
status = http.StatusFound
}
c.SetHeader("Location", location)
http.Redirect(c.Response, c.Request, location, status)
}
// Return returns response with auto detected Content-Type
func (c *Context) Return(body ...interface{}) error {
var tmprender render.Render
// auto detect response content-type from request header of accept
if len(c.Response.Header().Get("Content-Type")) == 0 {
accept := c.Request.Header.Get("Accept")
for _, enc := range strings.Split(accept, ",") {
switch {
case strings.Contains(enc, render.ContentTypeJSON), strings.Contains(enc, render.ContentTypeJSONP):
tmprender = render.NewJsonRender(c.Response)
case strings.Contains(enc, render.ContentTypeXML):
tmprender = render.NewXmlRender(c.Response)
}
if tmprender != nil {
break
}
}
}
// third, use default render
if tmprender == nil {
tmprender = render.NewDefaultRender(c.Response)
}
if len(body) > 0 {
return c.Render(tmprender, body[0])
}
return c.Render(tmprender, nil)
}
// HashedReturn returns response with ETag header calculated hash of response.Body dynamically
func (c *Context) HashedReturn(hasher crypto.Hash, body ...interface{}) error {
if len(body) > 0 {
return c.Render(render.NewHashRender(c.Response, hasher), body[0])
}
return c.Render(render.NewHashRender(c.Response, hasher), "")
}
// Text returns response with Content-Type: text/plain header
func (c *Context) Text(data interface{}) error {
return c.Render(render.NewTextRender(c.Response), data)
}
// String is alias of Text
func (c *Context) String(data interface{}) error {
return c.Render(render.NewTextRender(c.Response), data)
}
// JSON returns response with json codec and Content-Type: application/json header
func (c *Context) JSON(data interface{}) error {
return c.Render(render.NewJsonRender(c.Response), data)
}
// JSONP returns response with json codec and Content-Type: application/javascript header
func (c *Context) JSONP(callback string, data interface{}) error {
return c.Render(render.NewJsonpRender(c.Response, callback), data)
}
// XML returns response with xml codec and Content-Type: text/xml header
func (c *Context) XML(data interface{}) error {
return c.Render(render.NewXmlRender(c.Response), data)
}
// Render responses client with data rendered by Render
func (c *Context) Render(rr render.Render, data interface{}) error {
// always abort
c.Abort()
// currect response status code
if coder, ok := data.(StatusCoder); ok {
c.SetStatus(coder.StatusCode())
}
// currect response content-type header
if contentType := rr.ContentType(); contentType != "" {
c.SetHeader("Content-Type", contentType)
}
// flush header
c.Response.FlushHeader()
// invoke ResponseReady
if !c.responseReady.Run(c.Response, c.Request) {
return nil
}
// shortcut for nil data
if data == nil {
return nil
}
err := rr.Render(data)
if err != nil {
c.Logger.Errorf("%T.Render(?): %v", rr, err)
}
return err
}
// Next executes the remain filters in the chain.
//
// NOTE: It ONLY used in the filters!
func (c *Context) Next() {
// is aborted?
if c.cursor >= math.MaxInt8 {
return
}
c.cursor++
if c.cursor >= 0 && c.cursor < int8(len(c.filters)) {
c.filters[c.cursor](c)
}
}
// Abort forces to stop call chain.
func (c *Context) Abort() {
c.cursor = math.MaxInt8
}
// run starting request chan with new envs.
func (c *Context) run(handler http.Handler, filters []Middleware, responseReady *hooks.HookList) {
c.mux.Lock()
defer c.mux.Unlock()
// reset internal
c.settings = nil
c.frozenSettings = nil
c.filters = filters
c.responseReady = responseReady
c.issuedAt = time.Now()
c.cursor = -1
// start chains
c.Next()
// ghost for non render
if c.cursor >= 0 && c.cursor < math.MaxInt8 {
c.Abort()
// invoke ResponseReady
if !c.responseReady.Run(c.Response, c.Request) {
return
}
// invoke http.Handler if defined
if handler != nil {
handler.ServeHTTP(c.Response, c.Request)
} else {
// response status code always
c.Response.FlushHeader()
}
}
}