/
HttpContext.go
366 lines (318 loc) 路 8.54 KB
/
HttpContext.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
354
355
356
357
358
359
360
361
362
363
364
365
366
package Context
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"github.com/maxzhang1985/yoyogo/ActionResult"
"github.com/maxzhang1985/yoyogo/DependencyInjection"
"github.com/maxzhang1985/yoyogo/Utils"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"sync"
)
const (
defaultTagName = "param"
jsonTagName = "json"
)
type M = map[string]string
type HttpContext struct {
Request *http.Request
Response *responseWriter
RouterData url.Values
RequiredServices DependencyInjection.IServiceProvider
store map[string]interface{}
storeMutex *sync.RWMutex
Result interface{}
}
func NewContext(w http.ResponseWriter, r *http.Request, sp DependencyInjection.IServiceProvider) *HttpContext {
ctx := &HttpContext{}
ctx.init(w, r, sp)
return ctx
}
func (ctx *HttpContext) init(w http.ResponseWriter, r *http.Request, sp DependencyInjection.IServiceProvider) {
ctx.storeMutex = new(sync.RWMutex)
ctx.Response = &responseWriter{w, 0, 0, nil}
ctx.Request = r
ctx.RouterData = url.Values{}
ctx.RequiredServices = sp
ctx.storeMutex.Lock()
ctx.store = nil
ctx.storeMutex.Unlock()
}
//Set data in context.
func (ctx *HttpContext) SetItem(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 *HttpContext) GetItem(key string) interface{} {
ctx.storeMutex.RLock()
v := ctx.store[key]
ctx.storeMutex.RUnlock()
return v
}
//Set Cookie value
func (ctx *HttpContext) SetCookie(name, value string) {
cookie := &http.Cookie{
Name: name,
Value: value,
Path: "/",
MaxAge: 0,
HttpOnly: true,
}
ctx.Response.Header().Add("Set-Cookie", cookie.String())
}
//Get Cookie by Name
func (ctx *HttpContext) GetCookie(name string) string {
cookie, err := ctx.Request.Cookie(name)
if err != nil {
return ""
}
return url.QueryEscape(cookie.Value)
}
func (c *HttpContext) Header(key, value string) {
if value == "" {
c.Response.Header().Del(key)
return
}
c.Response.Header().Set(key, value)
}
//Get Post Params
func (ctx *HttpContext) PostForm() url.Values {
_ = ctx.Request.ParseForm()
return ctx.Request.PostForm
}
func (ctx *HttpContext) PostMultipartForm() url.Values {
_ = ctx.Request.ParseMultipartForm(32 << 20)
return ctx.Request.MultipartForm.Value
}
func (ctx *HttpContext) PostJsonForm() url.Values {
ret := url.Values{}
var jsonMap map[string]interface{}
body := ctx.PostBody()
_ = json.Unmarshal(body, &jsonMap)
var strVal string
for key, value := range jsonMap {
switch value.(type) {
case int32:
case int64:
strVal = strconv.Itoa(value.(int))
break
case float64:
strVal = strconv.FormatFloat(value.(float64), 'f', -1, 64)
break
default:
strVal = fmt.Sprint(value)
}
ret.Add(key, strVal)
}
return ret
}
func (ctx *HttpContext) GetAllParam() url.Values {
form := url.Values{}
content_type := ctx.Request.Header.Get("Content-Type")
if strings.HasPrefix(content_type, MIMEApplicationForm) {
form = ctx.PostForm()
} else if strings.HasPrefix(content_type, MIMEMultipartForm) {
form = ctx.PostMultipartForm()
} else if strings.HasPrefix(content_type, MIMEApplicationJSON) {
form = ctx.PostJsonForm()
}
Utils.MergeMap(form, ctx.QueryStrings())
Utils.MergeMap(form, ctx.RouterData)
return form
}
//Get Post Param
func (ctx *HttpContext) Param(name string) string {
form := ctx.GetAllParam()
if form[name] != nil {
return form[name][0]
}
return ""
}
// PostBody returns data from the POST or PUT request body
func (ctx *HttpContext) PostBody() []byte {
bts, err := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bts))
if err != nil {
return []byte{}
}
return bts
}
func (ctx *HttpContext) Bind(i interface{}) (err error) {
req := ctx.Request
ctype := req.Header.Get(HeaderContentType)
if req.Body == nil {
err = errors.New("request body can't be empty")
return err
}
err = errors.New("request unsupported MediaType -> " + ctype)
tagName := defaultTagName
switch {
case strings.HasPrefix(ctype, MIMEApplicationXML):
err = xml.Unmarshal(ctx.PostBody(), i)
case strings.HasPrefix(ctype, MIMEApplicationJSON):
//tagName = jsonTagName
default:
// check is use json tag, fixed for issue #91
//tagName = defaultTagName
// no check content type for fixed issue #6
}
err = ConvertMapToStruct(tagName, i, ctx.GetAllParam())
return err
}
// RemoteIP RemoteAddr to an "IP" address
func (ctx *HttpContext) RemoteIP() string {
host, _, _ := net.SplitHostPort(ctx.Request.RemoteAddr)
return host
}
// RealIP returns the first ip from 'X-Forwarded-For' or 'X-Real-IP' header key
// if not exists data, returns request.RemoteAddr
// fixed for #164
func (ctx *HttpContext) RealIP() string {
if ip := ctx.Request.Header.Get(HeaderXForwardedFor); ip != "" {
return strings.Split(ip, ", ")[0]
}
if ip := ctx.Request.Header.Get(HeaderXRealIP); ip != "" {
return ip
}
host, _, _ := net.SplitHostPort(ctx.Request.RemoteAddr)
return host
}
// FullRemoteIP RemoteAddr to an "IP:port" address
func (ctx *HttpContext) FullRemoteIP() string {
fullIp := ctx.Request.RemoteAddr
return fullIp
}
// IsAJAX returns if it is a ajax request
func (ctx *HttpContext) IsAJAX() bool {
return strings.Contains(ctx.Request.Header.Get(HeaderXRequestedWith), "XMLHttpRequest")
}
func (ctx *HttpContext) IsWebsocket() bool {
if strings.Contains(strings.ToLower(ctx.Request.Header.Get("Connection")), "upgrade") &&
strings.EqualFold(ctx.Request.Header.Get("Upgrade"), "websocket") {
return true
}
return false
}
// Url get request url
func (ctx *HttpContext) Url() string {
return ctx.Request.URL.String()
}
// Get Query string
func (ctx *HttpContext) QueryStrings() url.Values {
queryForm, err := url.ParseQuery(ctx.Request.URL.RawQuery)
if err == nil {
return queryForm
}
return nil
}
// Get Query String By Key
// GET /path?id=1234&name=Manu&value=
// c.Query("id") == "1234"
// c.Query("name") == "Manu"
// c.Query("value") == ""
// c.Query("wtf") == ""
func (ctx *HttpContext) Query(key string) string {
return ctx.QueryStrings().Get(key)
}
func (ctx *HttpContext) QueryStringOrDefault(key string, defaultval string) string {
val := ctx.QueryStrings().Get(key)
if val == "" {
val = defaultval
}
return val
}
// Redirect redirects the request
func (ctx *HttpContext) Redirect(code int, url string) {
http.Redirect(ctx.Response, ctx.Request, url, code)
}
// Path returns URL Path string.
func (ctx *HttpContext) Path() string {
return ctx.Request.URL.Path
}
// Referer returns request referer.
func (ctx *HttpContext) Referer() string {
return ctx.Request.Header.Get("Referer")
}
// UserAgent returns http request UserAgent
func (ctx *HttpContext) UserAgent() string {
return ctx.Request.Header.Get("User-Agent")
}
//Get Http Method.
func (ctx *HttpContext) Method() string {
return ctx.Request.Method
}
//Get Http Status Code.
func (ctx *HttpContext) GetStatus() int {
return ctx.Response.status
}
// Status sets the HTTP response code.
func (ctx *HttpContext) Status(code int) {
ctx.Response.WriteHeader(code)
}
// FormFile gets file from request.
func (ctx *HttpContext) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
return ctx.Request.FormFile(key)
}
// SaveFile saves the form file and
// returns the filename.
func (ctx *HttpContext) 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
}
// Write Error Response.
func (ctx *HttpContext) Error(code int, error string) {
http.Error(ctx.Response, error, code)
}
// Write Byte[] Response.
func (ctx *HttpContext) Write(data []byte) (n int, err error) {
return ctx.Response.Write(data)
}
func bodyAllowedForStatus(status int) bool {
switch {
case status >= 100 && status <= 199:
return false
case status == http.StatusNoContent:
return false
case status == http.StatusNotModified:
return false
}
return true
}
// ActionResult writes the response headers and calls render.ActionResult to render data.
func (c *HttpContext) Render(code int, r ActionResult.IActionResult) {
c.Status(code)
if !bodyAllowedForStatus(code) {
r.WriteContentType(c.Response)
c.Response.WriteHeaderNow()
return
}
if err := r.Render(c.Response); err != nil {
panic(err)
}
}