forked from cookieY/yee
/
context.go
353 lines (309 loc) · 7.48 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
package yee
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
)
const abortIndex int8 = math.MaxInt8 / 2
// Context is the default implementation interface of context
type Context interface {
Request() *http.Request
Response() ResponseWriter
HTML(code int, html string) (err error)
JSON(code int, i interface{}) error
String(code int, s string) error
Status(code int)
QueryParam(name string) string
QueryString() string
SetHeader(key string, value string)
AddHeader(key string, value string)
GetHeader(key string) string
FormValue(name string) string
FormParams() (url.Values, error)
FormFile(name string) (*multipart.FileHeader, error)
File(file string) error
MultipartForm() (*multipart.Form, error)
Redirect(code int, uri string) error
Params(name string) string
RequestURI() string
Scheme() string
IsTLS() bool
Next()
HTMLTml(code int, tml string) (err error)
QueryParams() map[string][]string
Bind(i interface{}) error
Cookie(name string) (*http.Cookie, error)
SetCookie(cookie *http.Cookie)
Cookies() []*http.Cookie
Get(key string) interface{}
Put(key string, values interface{})
ServerError(code int, defaultMessage string) error
RemoteIP() string
Logger() Logger
Reset()
}
type context struct {
engine *Core
writermem responseWriter
w ResponseWriter
r *http.Request
path string
method string
code int
queryList url.Values // cache url.Values
params *Params
Param Params
// middleware
handlers HandlersChain
index int
store map[string]interface{}
lock sync.RWMutex
noRewrite bool
}
func (c *context) Reset() {
c.index = -1
c.handlers = c.engine.noRoute
}
func (c *context) Bind(i interface{}) error {
return c.engine.bind.Bind(i, c)
}
func (c *context) reset() { // reset context members
c.w = &c.writermem
c.Param = c.Param[0:0]
c.handlers = nil
c.index = -1
c.path = ""
// when context reset clear queryList cache .
// cause if not clear cache the queryParams results will mistake
c.queryList = nil
c.store = nil
*c.params = (*c.params)[0:0]
}
func (c *context) Next() {
c.index++
s := len(c.handlers)
for ; c.index < s; c.index++ {
_ = c.handlers[c.index](c)
if c.w.Written() {
break
}
}
}
func (c *context) Logger() Logger {
return c.engine.l
}
func (c *context) ServerError(code int, defaultMessage string) error {
c.writermem.status = code
if c.writermem.Written() {
return errors.New("headers were already written")
}
if c.writermem.Status() == code {
c.writermem.Header()["Content-Type"] = []string{MIMETextPlainCharsetUTF8}
c.Logger().Error(fmt.Sprintf("%s %s", c.r.URL, defaultMessage))
_, err := c.w.Write([]byte(defaultMessage))
if err != nil {
return fmt.Errorf("cannot write message to writer during serve error: %v", err)
}
return nil
}
c.writermem.WriteHeaderNow()
return nil
}
func (c *context) Put(key string, values interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
if c.store == nil {
c.store = make(map[string]interface{})
}
c.store[key] = values
}
func (c *context) Get(key string) interface{} {
c.lock.RLock()
defer c.lock.RUnlock()
return c.store[key]
}
func (c *context) Request() *http.Request {
return c.r
}
func (c *context) Response() ResponseWriter {
return c.w
}
func (c *context) RemoteIP() string {
if ip := c.r.Header.Get(HeaderXForwardedFor); ip != "" {
i := strings.IndexAny(ip, ", ")
if i > 0 {
return ip[:i]
}
}
if ip := c.r.Header.Get(HeaderXRealIP); ip != "" {
return ip
}
ip, _, _ := net.SplitHostPort(c.r.RemoteAddr)
return ip
}
func (c *context) HTML(code int, html string) (err error) {
return c.HTMLBlob(code, []byte(html))
}
func (c *context) HTMLTml(code int, tml string) (err error) {
s, e := ioutil.ReadFile(tml)
if e != nil {
panic(e)
}
return c.HTMLBlob(code, s)
}
func (c *context) HTMLBlob(code int, b []byte) (err error) {
return c.Blob(code, MIMETextHTMLCharsetUTF8, b)
}
func (c *context) Blob(code int, contentType string, b []byte) (err error) {
if !c.writermem.Written() {
c.writeContentType(contentType)
c.w.WriteHeader(code)
if _, err = c.w.Write(b); err != nil {
c.Logger().Error(err.Error())
}
}
return
}
func (c *context) JSON(code int, i interface{}) (err error) {
if !c.writermem.Written() {
enc := json.NewEncoder(c.w)
c.writeContentType(MIMEApplicationJSONCharsetUTF8)
c.w.WriteHeader(code)
return enc.Encode(i)
}
return
}
func (c *context) String(code int, s string) error {
return c.Blob(code, MIMETextPlainCharsetUTF8, []byte(s))
}
func (c *context) Status(code int) {
c.w.WriteHeader(code)
}
func (c *context) SetHeader(key string, value string) {
c.w.Header().Set(key, value)
}
func (c *context) AddHeader(key string, value string) {
c.w.Header().Add(key, value)
}
func (c *context) GetHeader(key string) string {
return c.r.Header.Get(key)
}
func (c *context) Params(name string) string {
for _, i := range *c.params {
if i.Key == name {
return i.Value
}
}
return ""
}
func (c *context) Cookie(name string) (*http.Cookie, error) {
return c.r.Cookie(name)
}
func (c *context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.w, cookie)
}
func (c *context) Cookies() []*http.Cookie {
return c.r.Cookies()
}
func (c *context) QueryParams() map[string][]string {
return c.r.URL.Query()
}
func (c *context) QueryParam(name string) string {
if c.queryList == nil {
c.queryList = c.r.URL.Query()
}
return c.queryList.Get(name)
}
func (c *context) QueryString() string {
return c.r.URL.RawQuery
}
func (c *context) FormValue(name string) string {
return c.r.FormValue(name)
}
func (c *context) FormParams() (url.Values, error) {
if strings.HasPrefix(c.r.Header.Get(HeaderContentType), MIMEMultipartForm) {
if err := c.r.ParseMultipartForm(defaultMemory); err != nil {
return nil, err
}
} else {
if err := c.r.ParseForm(); err != nil {
return nil, err
}
}
return c.r.Form, nil
}
func (c *context) FormFile(name string) (*multipart.FileHeader, error) {
_, fd, err := c.r.FormFile(name)
return fd, err
}
func (c *context) File(file string) error {
fd, err := os.Open(file)
if err != nil {
return err
}
defer fd.Close()
f, _ := fd.Stat()
if f.IsDir() {
file = filepath.Join(file, indexPage)
fd, err = os.Open(file)
if err != nil {
return ErrNotFoundHandler
}
defer fd.Close()
if f, err = fd.Stat(); err != nil {
return err
}
}
http.ServeContent(c.Response(), c.Request(), f.Name(), f.ModTime(), fd)
return nil
}
func (c *context) MultipartForm() (*multipart.Form, error) {
err := c.r.ParseMultipartForm(defaultMemory)
return c.r.MultipartForm, err
}
func (c *context) RequestURI() string {
return c.r.RequestURI
}
func (c *context) Scheme() string {
scheme := "http"
if scheme := c.r.Header.Get(HeaderXForwardedProto); scheme != "" {
return scheme
}
if scheme := c.r.Header.Get(HeaderXForwardedProtocol); scheme != "" {
return scheme
}
if ssl := c.r.Header.Get(HeaderXForwardedSsl); ssl == "on" {
return "https"
}
if scheme := c.r.Header.Get(HeaderXUrlScheme); scheme != "" {
return scheme
}
return scheme
}
func (c *context) IsTLS() bool {
return c.r.TLS != nil
}
func (c *context) Redirect(code int, uri string) error {
if code < 300 || code > 308 {
return ErrInvalidRedirectCode
}
c.r.Header.Set(HeaderLocation, uri)
c.w.WriteHeader(code)
return nil
}
func (c *context) writeContentType(value string) {
header := c.w.Header()
if header.Get(HeaderContentType) == "" {
header.Set(HeaderContentType, value)
}
}