-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.go
280 lines (243 loc) · 6.74 KB
/
request.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
package request
import (
"bytes"
"net/http"
"net/url"
"strings"
"time"
"github.com/Nigel2392/router/v3/request/writer"
"github.com/Nigel2392/routevars"
)
const MESSAGE_COOKIE_NAME = "messages"
const NEXT_COOKIE_NAME = "next"
// Default request to be passed around the router.
type Request struct {
// Underlying http response writer.
Response writer.ClearableBufferedResponse
// Underlying http request.
Request *http.Request
// Default data to be passed to any possible templates.
Data *TemplateData
// URL Parameters set inside of the router.
URLParams URLParams
// The request form, which is filled when you call r.Form().
form url.Values
// The request JSON object, which handles returning json responses.
// This is mostly for semantic reasons.
JSON *_json
// The next url to redirect to.
next string
// Interfaces which can be set using the right middlewares.
// These interfaces are not set by default, but can be set by middleware.
User User
// Session can be set with middleware!
Session Session
// Logger can be set with middleware!
Logger Logger
// URL Func will be automatically set by the router.
URL func(method, name string) routevars.URLFormatter
}
// Initialize a new request.
func NewRequest(writer writer.ClearableBufferedResponse, request *http.Request, params URLParams) *Request {
var r = &Request{
Response: writer,
Request: request,
URLParams: params,
JSON: &_json{},
Data: NewTemplateData(),
}
r.Data.Request.url = func(s string, i ...interface{}) string {
return r.URL("ALL", s).Format(i...)
}
r.JSON.r = &r
return r
}
// Write to the response.
func (r *Request) Write(b []byte) (int, error) {
return r.Response.Write(b)
}
// Write a string to the response.
func (r *Request) WriteString(s string) (int, error) {
return r.Response.Write([]byte(s))
}
// Raise an error.
func (r *Request) Error(code int, err string) {
r.Response.Buffer().Reset()
for k := range r.Response.Header() {
r.Response.Header().Del(k)
}
http.Error(r.Response, err, code)
}
// Get the request method.
func (r *Request) Method() string {
return r.Request.Method
}
// Parse the form, and return the form values.
func (r *Request) Form() url.Values {
if r.form == nil {
r.Request.ParseForm()
r.form = r.Request.Form
}
return r.form
}
// Get a form file as a buffer.
func (r *Request) FormFileBuffer(name string) (*bytes.Buffer, error) {
m, _, err := r.Request.FormFile(name)
if err != nil {
return nil, err
}
var buf bytes.Buffer
buf.ReadFrom(m)
return &buf, nil
}
// Set a data value.
func (r *Request) SetData(key string, value interface{}) {
r.Data.Set(key, value)
}
// Get a data value.
func (r *Request) GetData(key string) interface{} {
return r.Data.Get(key)
}
// Get the Next url.
// This is the url that was set in the session/cookies.
// This is used to redirect back to the same page.
func (r *Request) Next() string {
if r.next != "" {
return r.next
}
if r.Session == nil {
// Set the next url if it exists.
// This is based on cookies.
if cookie, err := r.Request.Cookie(NEXT_COOKIE_NAME); err == nil {
r.next = cookie.Value
// Delete the cookie.
http.SetCookie(r.Response, &http.Cookie{
Name: NEXT_COOKIE_NAME,
Value: "",
Expires: time.Now().Add(-time.Hour),
})
}
} else {
// We have sessions! :)
if next, ok := r.Session.Get(NEXT_COOKIE_NAME).(string); ok {
r.next = next
r.Session.Delete(NEXT_COOKIE_NAME)
}
}
return r.next
}
// Reset the next data.
func (r *Request) ReSetNext() {
var next = r.Next()
if next != "" {
r.setNextURL(next)
}
}
func (r *Request) setNextData() {
if r.Session == nil {
// Set the messages in the cookies.
if r.Data != nil {
var cookie = &http.Cookie{
Name: MESSAGE_COOKIE_NAME,
Value: r.Data.Messages.Encode(),
Path: "/",
HttpOnly: true,
Expires: time.Now().Add(time.Hour * 24 * 30),
Secure: r.Request.TLS != nil,
MaxAge: 60 * 60 * 24 * 30,
}
http.SetCookie(r.Response, cookie)
}
} else {
// We have sessions! :)
if r.Data != nil {
r.Session.Set(MESSAGE_COOKIE_NAME, r.Data.Messages)
}
}
}
func (r *Request) setNextURL(next string) {
if r.Session == nil {
// If there is a next parameter, add it to the cookies.
if next != "" {
var cookie = &http.Cookie{
Name: NEXT_COOKIE_NAME,
Value: next,
Path: "/",
HttpOnly: true,
Expires: time.Now().Add(time.Hour * 24 * 30),
Secure: r.Request.TLS != nil,
MaxAge: 60 * 60 * 24 * 30,
}
http.SetCookie(r.Response, cookie)
}
} else {
if next != "" {
r.Session.Set(NEXT_COOKIE_NAME, next)
}
}
}
// Redirect to a URL.
// If the session is defined, the messages will be set in the session.
// If the `next` argument is given, it will be added to session, unless
// the session is not defined, the `next` parameter will be added to cookies.
// This means they will be carried across when rendering with request.Render().
// This will be set again after the redirect, when rendering in the default Data.
// Optionally you could obtain this by calling request.Next().
func (r *Request) Redirect(redirectURL string, statuscode int, next ...string) {
// Set the messages in the session/cookies for after the redirect.
if len(next) > 0 {
r.setNextURL(next[0])
}
r.setNextData()
// Redirect.
http.Redirect(r.Response, r.Request, redirectURL, statuscode)
}
// IP address of the request.
func (r *Request) IP() string {
var ip string
if ip = r.Request.Header.Get("X-Forwarded-For"); ip != "" {
goto parse
} else if ip = r.Request.Header.Get("X-Real-IP"); ip != "" {
goto parse
} else {
ip = r.Request.RemoteAddr
goto parse
}
parse:
// Parse the IP address.
if i := strings.Index(ip, ":"); i != -1 {
ip = ip[:i]
}
return ip
}
// Set cookies.
func (r *Request) SetCookies(cookies ...*http.Cookie) {
for _, cookie := range cookies {
http.SetCookie(r.Response, cookie)
}
}
// Get cookies.
func (r *Request) GetCookie(name string) (*http.Cookie, error) {
return r.Request.Cookie(name)
}
// Delete cookies.
func (r *Request) DeleteCookie(name string) {
http.SetCookie(r.Response, &http.Cookie{
Name: name,
Value: "",
Expires: time.Now().Add(-time.Hour),
Path: "/",
})
}
// Get a header.
func (r *Request) GetHeader(name string) string {
return r.Request.Header.Get(name)
}
// Set a header.
func (r *Request) SetHeader(name, value string) {
r.Response.Header().Set(name, value)
}
// Add a header.
func (r *Request) AddHeader(name, value string) {
AddHeader(r.Response, name, value)
}