forked from dolab/gogo
/
context.go
295 lines (229 loc) · 6.45 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
package gogo
import (
"crypto"
"math"
"net/http"
"strings"
"sync"
"time"
)
const (
abortIndex = math.MaxInt8 / 2
minSlowdownMs = 1 * time.Millisecond
)
type Context struct {
Response Responser
Request *http.Request
Params *AppParams
Server *AppServer
Config *AppConfig
Logger Logger
mux sync.RWMutex
settings map[string]interface{}
frozenSettings map[string]interface{}
writer Response
handlers []Middleware
index int8
startedAt time.Time
downAfter time.Time
}
func NewContext(server *AppServer) *Context {
return &Context{
Server: server,
index: -1,
}
}
// Set associates a new value with key for the context
func (c *Context) Set(key string, value interface{}) {
c.mux.Lock()
if c.settings == nil {
c.settings = make(map[string]interface{})
}
c.settings[key] = value
c.mux.Unlock()
}
// Get returns a value of the key
func (c *Context) Get(key string) (interface{}, bool) {
c.mux.RLock()
defer c.mux.RUnlock()
if c.settings == nil {
return nil, false
}
value, ok := c.settings[key]
return value, ok
}
// MustGet returns a value of key or panic when key doesn't exist
func (c *Context) MustGet(key string) interface{} {
value, ok := c.Get(key)
if !ok {
c.Logger.Panicf("Key %s doesn't exist", key)
}
return value
}
// SetFinal associates a value with key for the context and freezes following update
func (c *Context) SetFinal(key string, value interface{}) error {
c.mux.Lock()
defer c.mux.Unlock()
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) (interface{}, bool) {
c.mux.RLock()
defer c.mux.RUnlock()
if c.frozenSettings == nil {
return nil, false
}
value, ok := c.frozenSettings[key]
return value, ok
}
// MustSetFinal associates a value with key for the context and freezes following update,
// it panics if key is duplicated.
func (c *Context) MustSetFinal(key string, value interface{}) {
c.mux.Lock()
defer c.mux.Unlock()
if c.frozenSettings == nil {
c.frozenSettings = make(map[string]interface{})
}
if _, ok := c.frozenSettings[key]; ok {
c.Logger.Panicf("Freeze key %s duplicated!", key)
}
c.frozenSettings[key] = value
}
// MustGetFinal returns a frozen value of key or panic when key doesn't exist
func (c *Context) MustGetFinal(key string) interface{} {
value, ok := c.GetFinal(key)
if !ok {
c.Logger.Panicf("Freeze key %s doesn't exist", key)
}
return value
}
// RequestURI returns request raw uri
func (c *Context) RequestURI() string {
return c.Request.RequestURI
}
// RequestID returns x-request-id value
func (c *Context) RequestID() string {
return c.Logger.RequestId()
}
// 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 request header value of specified key
func (c *Context) RawHeader(key string) string {
for yek, val := range c.Request.Header {
if key == yek {
return strings.Join(val, ",")
}
}
return ""
}
// 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)
}
// SetHeaders 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 following default Content-Type header
func (c *Context) Return(body ...interface{}) error {
if len(body) > 0 {
return c.Render(NewDefaultRender(c.Response), body[0])
}
return c.Render(NewDefaultRender(c.Response), "")
}
// 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(NewHashRender(c.Response, hasher), body[0])
}
return c.Render(NewHashRender(c.Response, hasher), "")
}
// Text returns response with Content-Type: text/plain header
func (c *Context) Text(data interface{}) error {
return c.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(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(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(NewXmlRender(c.Response), data)
}
func (c *Context) Render(w Render, data interface{}) error {
// always abort
c.Abort()
// NOTE: its only ensure AT LEAST but EQUAL!!!
if delta := c.downAfter.Sub(time.Now()); delta > minSlowdownMs {
ticker := time.NewTicker(delta)
select {
case <-ticker.C:
ticker.Stop()
}
}
err := w.Render(data)
if err != nil {
c.Logger.Errorf("%T.Render(?): %v", w, err)
c.Response.WriteHeader(http.StatusInternalServerError)
}
return err
}
// Next executes the remain handlers in the chain.
// NOTE: It ONLY used in the middlewares!
func (c *Context) Next() {
c.index++
for c.index < int8(len(c.handlers)) {
c.handlers[c.index](c)
c.index++
}
}
// Abort forces to stop call chain.
func (c *Context) Abort() {
c.index = abortIndex
}