-
Notifications
You must be signed in to change notification settings - Fork 30
/
context.go
316 lines (280 loc) · 8.21 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
package golf
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"strings"
"time"
)
// Context is a wrapper of http.Request and http.ResponseWriter.
type Context struct {
// http.Request
Request *http.Request
// http.ResponseWriter
Response http.ResponseWriter
// URL Parameter
Params Parameter
// HTTP status code
statusCode int
// The application
App *Application
// Session instance for the current context.
Session Session
// Indicating if the response is already sent.
IsSent bool
// Indicating loader of the template
templateLoader string
}
// NewContext creates a Golf.Context instance.
func NewContext(req *http.Request, res http.ResponseWriter, app *Application) *Context {
ctx := new(Context)
ctx.Request = req
ctx.Request.ParseForm()
ctx.Response = res
ctx.App = app
ctx.statusCode = 200
// ctx.Header["Content-Type"] = "text/html;charset=UTF-8"
ctx.Request.ParseForm()
ctx.IsSent = false
return ctx
}
func (ctx *Context) reset() {
ctx.statusCode = 200
ctx.IsSent = false
}
func (ctx *Context) generateSession() Session {
s, err := ctx.App.SessionManager.NewSession()
if err != nil {
return nil
}
// Session lifetime should be configurable.
ctx.SetCookie("sid", s.SessionID(), 3600)
return s
}
func (ctx *Context) retrieveSession() {
var s Session
sid, err := ctx.Cookie("sid")
if err != nil {
s = ctx.generateSession()
} else {
s, err = ctx.App.SessionManager.Session(sid)
if err != nil {
s = ctx.generateSession()
}
}
ctx.Session = s
}
// SendStatus takes an integer and sets the response status to the integer given.
func (ctx *Context) SendStatus(statusCode int) {
ctx.statusCode = statusCode
ctx.Response.WriteHeader(statusCode)
}
// StatusCode returns the status code that golf has sent.
func (ctx *Context) StatusCode() int {
return ctx.statusCode
}
// SetHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key.
func (ctx *Context) SetHeader(key, value string) {
ctx.Response.Header().Set(key, value)
}
// AddHeader adds the key, value pair to the header. It appends to any existing values associated with key.
func (ctx *Context) AddHeader(key, value string) {
ctx.Response.Header().Add(key, value)
}
// Header gets the first value associated with the given key. If there are no values associated with the key, Get returns "".
func (ctx *Context) Header(key string) string {
return ctx.Request.Header.Get(key)
}
// Query method retrieves the form data, return empty string if not found.
func (ctx *Context) Query(key string, index ...int) (string, error) {
if val, ok := ctx.Request.Form[key]; ok {
if len(index) == 1 {
return val[index[0]], nil
}
return val[0], nil
}
return "", errors.New("Query key not found")
}
// Param method retrieves the parameters from url
// If the url is /:id/, then id can be retrieved by calling `ctx.Param(id)`
func (ctx *Context) Param(key string) string {
val, _ := ctx.Params.ByName(key)
return val
}
// Redirect method sets the response as a 302 redirection.
func (ctx *Context) Redirect(url string) {
ctx.SetHeader("Location", url)
ctx.SendStatus(302)
}
// Redirect301 method sets the response as a 301 redirection.
func (ctx *Context) Redirect301(url string) {
ctx.SetHeader("Location", url)
ctx.SendStatus(301)
}
// Cookie returns the value of the cookie by indicating the key.
func (ctx *Context) Cookie(key string) (string, error) {
c, err := ctx.Request.Cookie(key)
if err != nil {
return "", err
}
return c.Value, nil
}
// SetCookie set cookies for the request. If expire is 0, create a session cookie.
func (ctx *Context) SetCookie(key string, value string, expire int) {
now := time.Now()
cookie := &http.Cookie{
Name: key,
Value: value,
Path: "/",
MaxAge: expire,
}
if expire != 0 {
expireTime := now.Add(time.Duration(expire) * time.Second)
cookie.Expires = expireTime
}
http.SetCookie(ctx.Response, cookie)
}
// JSON Sends a JSON response.
func (ctx *Context) JSON(obj interface{}) {
json, err := json.Marshal(obj)
if err != nil {
panic(err)
}
ctx.SetHeader("Content-Type", "application/json")
ctx.Send(json)
}
// JSONIndent Sends a JSON response, indenting the JSON as desired.
func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) {
jsonIndented, err := json.MarshalIndent(obj, prefix, indent)
if err != nil {
panic(err)
}
ctx.SetHeader("Content-Type", "application/json")
ctx.Send(jsonIndented)
}
// Send the response immediately. Set `ctx.IsSent` to `true` to make
// sure that the response won't be sent twice.
func (ctx *Context) Send(body interface{}) {
if ctx.IsSent {
return
}
switch body.(type) {
case []byte:
ctx.Response.Write(body.([]byte))
case string:
ctx.Response.Write([]byte(body.(string)))
case *bytes.Buffer:
ctx.Response.Write(body.(*bytes.Buffer).Bytes())
default:
panic(fmt.Errorf("Body type not supported"))
}
ctx.IsSent = true
}
func (ctx *Context) requestHeader(key string) string {
if values, _ := ctx.Request.Header[key]; len(values) > 0 {
return values[0]
}
return ""
}
// ClientIP implements a best effort algorithm to return the real client IP, it parses
// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
// This method is taken from https://github.com/gin-gonic/gin
func (ctx *Context) ClientIP() string {
clientIP := strings.TrimSpace(ctx.requestHeader("X-Real-Ip"))
if len(clientIP) > 0 {
return clientIP
}
clientIP = ctx.requestHeader("X-Forwarded-For")
if index := strings.IndexByte(clientIP, ','); index >= 0 {
clientIP = clientIP[0:index]
}
clientIP = strings.TrimSpace(clientIP)
if len(clientIP) > 0 {
return clientIP
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(ctx.Request.RemoteAddr)); err == nil {
return ip
}
return ""
}
// Abort method returns an HTTP Error by indicating the status code, the corresponding
// handler inside `App.errorHandler` will be called, if user has not set
// the corresponding error handler, the defaultErrorHandler will be called.
func (ctx *Context) Abort(statusCode int, data ...map[string]interface{}) {
ctx.App.handleError(ctx, statusCode, data...)
}
// Loader method sets the template loader for this context. This should be done before calling
// `ctx.Render`.
func (ctx *Context) Loader(name string) *Context {
ctx.templateLoader = name
return ctx
}
func (ctx *Context) getRawXSRFToken() string {
token, err := ctx.Cookie("_xsrf")
if err != nil {
return ""
}
return token
}
func (ctx *Context) checkXSRFToken() bool {
token := ctx.Request.FormValue("xsrf_token")
if token == "" {
return false
}
_, tokenA, _ := decodeXSRFToken(token)
_, tokenB, _ := decodeXSRFToken(ctx.getRawXSRFToken())
return compareToken(tokenA, tokenB)
}
func (ctx *Context) xsrfToken() string {
maskedToken := ctx.getRawXSRFToken()
if maskedToken == "" {
maskedToken = newXSRFToken()
ctx.SetCookie("_xsrf", maskedToken, 3600)
}
_, tokenBytes, err := decodeXSRFToken(maskedToken)
if err != nil {
maskedToken = newXSRFToken()
ctx.SetCookie("_xsrf", maskedToken, 3600)
_, tokenBytes, _ = decodeXSRFToken(maskedToken)
}
maskBytes := randomBytes(4)
maskedTokenBytes := append(maskBytes, websocketMask(maskBytes, tokenBytes)...)
return hex.EncodeToString(maskedTokenBytes)
}
// Render a template file using the built-in Go template engine.
func (ctx *Context) Render(file string, data ...map[string]interface{}) {
if ctx.templateLoader == "" {
panic(fmt.Errorf("Template loader has not been set"))
}
var renderData map[string]interface{}
if len(data) == 0 {
renderData = make(map[string]interface{})
} else {
renderData = data[0]
}
renderData["xsrf_token"] = ctx.xsrfToken()
content, err := ctx.App.View.Render(ctx.templateLoader, file, renderData)
if err != nil {
panic(err)
}
ctx.Send(content)
}
// RenderFromString renders a input string.
func (ctx *Context) RenderFromString(tplSrc string, data ...map[string]interface{}) {
var renderData map[string]interface{}
if len(data) == 0 {
renderData = make(map[string]interface{})
} else {
renderData = data[0]
}
renderData["xsrf_token"] = ctx.xsrfToken()
content, e := ctx.App.View.RenderFromString(ctx.templateLoader, tplSrc, renderData)
if e != nil {
panic(e)
}
ctx.Send(content)
}