-
Notifications
You must be signed in to change notification settings - Fork 5
/
context.go
239 lines (211 loc) · 5.29 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
package sgo
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path"
"sync"
)
// Context provide a HTTP context for SGo.
type Context struct {
sg *SGo
Req *http.Request
Resp *responseWriter
handlers []HandlerFunc
store map[string]interface{}
storeMutex *sync.RWMutex
handlerState int
}
// NewContext .
func NewContext(w http.ResponseWriter, r *http.Request, sg *SGo) *Context {
ctx := &Context{}
ctx.sg = sg
ctx.storeMutex = new(sync.RWMutex)
ctx.handlers = make([]HandlerFunc, len(sg.Middlewares), len(sg.Middlewares)+3)
copy(ctx.handlers, sg.Middlewares)
ctx.Init(w, r)
return ctx
}
// Init the context gotten from sync pool.
func (ctx *Context) Init(w http.ResponseWriter, r *http.Request) {
ctx.Resp = &responseWriter{w, 0}
ctx.Req = r
ctx.handlers = ctx.handlers[:len(ctx.sg.Middlewares)]
ctx.handlerState = 0
ctx.storeMutex.Lock()
ctx.store = nil
ctx.storeMutex.Unlock()
}
// Next execute next middleware or router.
func (ctx *Context) Next() {
if ctx.handlerState < len(ctx.handlers) {
i := ctx.handlerState
ctx.handlerState++
if err := ctx.handlers[i](ctx); err != nil {
ctx.Error(500, err.Error())
}
}
}
// Set var in context.
func (ctx *Context) Set(key string, val interface{}) {
ctx.storeMutex.Lock()
if ctx.store == nil {
ctx.store = make(map[string]interface{})
}
ctx.store[key] = val
ctx.storeMutex.Unlock()
}
// Get data in context.
func (ctx *Context) Get(key string) interface{} {
ctx.storeMutex.RLock()
v := ctx.store[key]
ctx.storeMutex.RUnlock()
return v
}
// Gets all data in context.
func (ctx *Context) Gets() map[string]interface{} {
ctx.storeMutex.RLock()
vals := make(map[string]interface{})
for k, v := range ctx.store {
vals[k] = v
}
ctx.storeMutex.RUnlock()
return vals
}
// SetCookie is used for jwt.
func (ctx *Context) SetCookie(name, value string) {
cookie := &http.Cookie{
Name: name,
Value: value,
Path: "/",
HttpOnly: true,
MaxAge: 0,
}
ctx.Resp.Header().Add("Set-Cookie", cookie.String())
}
// GetCookie .
func (ctx *Context) GetCookie(name string) string {
cookie, err := ctx.Req.Cookie(name)
if err != nil {
return ""
}
v, _ := url.QueryUnescape(cookie.Value)
return v
}
// Params returns all params
func (ctx *Context) Params() url.Values {
return ctx.Req.Form
}
// Param returns specific params
func (ctx *Context) Param(key string) string {
if ctx.Params()[key] != nil {
return ctx.Params()[key][0]
}
return ""
}
// Method .
func (ctx *Context) Method() string {
return ctx.Req.Method
}
//Status Code.
func (ctx *Context) Status() int {
return ctx.Resp.status
}
// FormFile gets file from request.
func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
return ctx.Req.FormFile(key)
}
// SaveFile saves the form file and
// returns the filename.
func (ctx *Context) SaveFile(name, saveDir string) (string, error) {
fr, handle, err := ctx.FormFile(name)
if err != nil {
return "", err
}
defer fr.Close()
fw, err := os.OpenFile(path.Join(saveDir, handle.Filename), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return "", err
}
defer fw.Close()
_, err = io.Copy(fw, fr)
return handle.Filename, err
}
// Error .
func (ctx *Context) Error(code int, error string) {
http.Error(ctx.Resp, error, code)
ctx.handlerState = len(ctx.handlers) // break handlers chain.
}
// Write Response.
func (ctx *Context) Write(data []byte) (n int, err error) {
return ctx.Resp.Write(data)
}
// Text response text data.
func (ctx *Context) Text(code int, body string) error {
ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
ctx.Resp.WriteHeader(code)
_, err := ctx.Resp.Write([]byte(body))
return err
}
// JSON response JSON data.
// {flag: 1, msg: "success", data: ...}
func (ctx *Context) JSON(code, flag int, msg string, data interface{}) error {
m := map[string]interface{}{
"msg": msg,
"data": data,
"flag": flag,
}
j, err := json.Marshal(m)
if err != nil {
return err
}
ctx.Resp.Header().Set("Content-Type", "application/json")
ctx.Resp.WriteHeader(code)
ctx.Resp.Write(j)
return nil
}
// JSONP return JSONP data.
func (ctx *Context) JSONP(code int, callback string, data interface{}) error {
j, err := json.Marshal(data)
if err != nil {
return err
}
ctx.Resp.Header().Set("Content-Type", "application/javascript; charset=utf-8")
ctx.Resp.WriteHeader(code)
ctx.Resp.Write([]byte(callback + "("))
ctx.Resp.Write(j)
ctx.Resp.Write([]byte(");"))
return nil
}
// Render sgo.templates with stored data.
func (ctx *Context) Render(code int, tplname string) error {
buf := new(bytes.Buffer)
err := ctx.sg.Templates.Render(buf, tplname, ctx.Gets())
if err != nil {
return err
}
ctx.Resp.Header().Set("Content-Type", "text/html")
ctx.Resp.WriteHeader(code)
ctx.Resp.Write(buf.Bytes())
return nil
}
// Redirect redirects the request
func (ctx *Context) Redirect(code int, url string) {
http.Redirect(ctx.Resp, ctx.Req, url, code)
}
// Path returns URL Path string.
func (ctx *Context) Path() string {
return ctx.Req.URL.Path
}
// Referer returns request referer.
func (ctx *Context) Referer() string {
return ctx.Req.Header.Get("Referer")
}
// UserAgent returns http request UserAgent
func (ctx *Context) UserAgent() string {
return ctx.Req.Header.Get("User-Agent")
}