-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.go
344 lines (283 loc) · 8.57 KB
/
content.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
package water
import (
"encoding/xml"
"errors"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
"github.com/meilihao/logx"
"github.com/meilihao/water/binding"
)
type H map[string]interface{}
func (ctx *Context) GetHeader(key string) string {
return ctx.Request.Header.Get(key)
}
func (ctx *Context) SetHeader(key, value string) {
ctx.Header().Set(key, value)
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
func (ctx *Context) Protocol() string {
switch s := ctx.GetHeader(HeaderXForwardedProto); s {
case "http", "https":
return s
}
if ctx.Request.TLS != nil {
return "https"
}
return "http"
}
// 301
func (ctx *Context) MovedPermanently(uri string) {
http.Redirect(ctx, ctx.Request, uri, http.StatusMovedPermanently)
}
// 302
func (ctx *Context) Found(uri string) {
http.Redirect(ctx, ctx.Request, uri, http.StatusFound)
}
// 304
func (ctx *Context) NotModified() {
ctx.Abort(http.StatusNotModified)
}
// 400
func (ctx *Context) BadRequest() {
ctx.Abort(http.StatusBadRequest)
}
// 401
func (ctx *Context) Unauthorized() {
ctx.Abort(http.StatusUnauthorized)
}
// 403
func (ctx *Context) Forbidden() {
ctx.Abort(http.StatusForbidden)
}
// 404
func (ctx *Context) NotFound() {
ctx.Abort(http.StatusNotFound)
}
// 500
func (ctx *Context) InternalServerError() {
ctx.Abort(http.StatusInternalServerError)
}
func (ctx *Context) Abort(code int) {
ctx.WriteHeader(code)
}
// http://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers
func (ctx *Context) NoCache() {
ctx.Header().Set(HeaderCacheControl, "no-cache, max-age=0, s-max-age=0, must-revalidate") // HTTP 1.1
ctx.Header().Set("Expires", "0") // Proxies.
}
func (ctx *Context) UserAgent() string {
return ctx.Request.Header.Get(HeaderUserAgent)
}
// IsAjax returns boolean of this request is generated by ajax.
func (ctx *Context) IsAjax() bool {
return ctx.Request.Header.Get(HeaderXRequestedWith) == MIMEXMLHttpRequest
}
func (ctx *Context) IsWebsocket() bool {
if strings.Contains(strings.ToLower(ctx.Request.Header.Get("Connection")), "upgrade") &&
strings.ToLower(ctx.Request.Header.Get("Upgrade")) == "websocket" {
return true
}
return false
}
// IP returns request client ip.
// if using proxy, return first proxy ip.
func (ctx *Context) RealIp() string {
return requestRealIp(ctx.Request)
}
// Proxy returns slice of proxy client ips.
func (ctx *Context) Proxy() []string {
return requestProxy(ctx.Request)
}
// ContentType returns the Content-Type header of the request.
func (ctx *Context) ContentType() string {
return filterFlags(ctx.Request.Header.Get("Content-Type"))
}
// BodyString returns content of request body in string.
func (ctx *Context) BodyString() (string, error) {
data, err := ctx.BodyBytes()
return string(data), err
}
// BodyBytes returns content of request body in bytes.
func (ctx *Context) BodyBytes() ([]byte, error) {
data, err := ioutil.ReadAll(ctx.Request.Body)
if err != nil {
return nil, err
}
ctx.Request.Body.Close()
return data, err
}
// ReadCloser returns a ReadCloser for request body, need Close()
func (ctx *Context) ReadCloser() io.ReadCloser {
return ctx.Request.Body
}
// File writes the specified file into the body stream.
func (ctx *Context) File(filepath string) {
http.ServeFile(ctx.ResponseWriter, ctx.Request, filepath)
}
func (ctx *Context) FormFile(name string) (multipart.File, *multipart.FileHeader, error) {
return ctx.Request.FormFile(name)
}
// SaveUploadedFile uploads the form file to specific dst.
// --- single file
// file, _ := c.FormFile("file")
// c.SaveUploadedFile(file, dst)
//
// curl -X POST http://localhost:8080/upload \
// -F "file=@/Users/appleboy/test.zip" \
// -H "Content-Type: multipart/form-data"
// --- Multiple files use:
// files := ctx.Request.MultipartForm.File["upload[]"]
// for _, file := range files {
// log.Println(file.Filename)
// // Upload the file to specific dst.
// c.SaveUploadedFile(file, dst)
// }
//
// curl -X POST http://localhost:8080/upload \
// -F "upload[]=@/Users/appleboy/test1.zip" \
// -F "upload[]=@/Users/appleboy/test2.zip" \
// -H "Content-Type: multipart/form-data"
func (ctx *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, src)
return err
}
func (ctx *Context) ServeFile(filePath string) {
http.ServeFile(ctx, ctx.Request, filePath)
}
func (ctx *Context) Download(fpath string, inline ...bool) error {
f, err := os.Open(fpath)
if err != nil {
return err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
if fi.IsDir() {
return errors.New("This is Dir.")
}
dispositionType := "attachment"
if len(inline) > 0 && inline[0] {
dispositionType = "inline"
}
ctx.Header().Set("Content-Description", "File Transfer")
ctx.Header().Set("Content-Type", "application/octet-stream")
ctx.Header().Set("Content-Transfer-Encoding", "binary")
ctx.Header().Set("Expires", "0")
ctx.Header().Set("Cache-Control", "must-revalidate")
ctx.Header().Set("Pragma", "public")
ctx.Header().Set(HeaderContentDisposition, contentDisposition(fi.Name(), dispositionType))
http.ServeContent(ctx, ctx.Request, fi.Name(), fi.ModTime(), f)
return nil
}
func (ctx *Context) Attachment(name string, modtime time.Time, content io.ReadSeeker, inline ...bool) {
dispositionType := "attachment"
if len(inline) > 0 && inline[0] {
dispositionType = "inline"
}
ctx.Header().Set(HeaderContentDisposition, contentDisposition(name, dispositionType))
http.ServeContent(ctx, ctx.Request, name, modtime, content)
}
func (ctx *Context) Stream(contentType string, r io.Reader) error {
ctx.Header().Set(HeaderContentType, contentType)
_, err := io.Copy(ctx, r)
return err
}
func (ctx *Context) String(code int, str string) {
ctx.WriteHeader(code)
ctx.Header().Set(HeaderContentType, MIMETextPlainCharsetUTF8)
ctx.Write([]byte(str))
}
func (ctx *Context) Data(code int, contentType string, data []byte) {
ctx.WriteHeader(code)
ctx.Header().Set(HeaderContentType, contentType)
ctx.Write(data)
}
// HTMLRaw not use render
func (ctx *Context) HTMLRaw(code int, str string) {
ctx.WriteHeader(code)
ctx.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8)
ctx.Write([]byte(str))
}
func (ctx *Context) JSON(code int, v interface{}) error {
ctx.WriteHeader(code)
ctx.Header().Set(HeaderContentType, MIMEApplicationJSONCharsetUTF8)
err := json.NewEncoder(ctx).Encode(v)
if err != nil {
logx.Warn(err)
}
return err
}
func (ctx *Context) XML(code int, v interface{}) error {
ctx.WriteHeader(code)
ctx.Header().Set(HeaderContentType, MIMEApplicationXMLCharsetUTF8)
err := xml.NewEncoder(ctx).Encode(v)
if err != nil {
logx.Warn(err)
}
return err
}
// Bind use http method and ContentType to decode req
func (ctx *Context) Bind(obj interface{}) error {
b := binding.NewBindinger(ctx.Request.Method, ctx.ContentType())
if b != binding.JSON && b != binding.XML {
ctx.ParseFormOrMultipartForm()
}
return ctx.BindWith(obj, b)
}
// BindWith use the assigned Bindinger to decode req
func (ctx *Context) BindWith(obj interface{}, b binding.Bindinger) error {
if b != binding.JSON && b != binding.XML {
ctx.ParseFormOrMultipartForm()
}
return b.Bind(ctx.Request, obj)
}
// HandlerName returns the last handler's name.
// For example if the handler is "_Users()", this function will return "main._Users".
func (ctx *Context) HandlerName() string {
return nameOfFunction(ctx.handlers[ctx.handlersLength-1])
}
// FullPath returns a matched route full path. For not found routes returns an empty string
func (ctx *Context) FullPath() string {
if ctx.endNode != nil {
return ctx.endNode.matchNode.uri
}
return ""
}
var (
// MultipartMemory
defaultMultipartMemory int64 = 32 << 20 // 32MB
)
// ParseFormOrMultipartForm parses the raw query from the URL.
func (ctx *Context) ParseFormOrMultipartForm() {
if ctx.parsedParams {
return
}
ctx.parsedParams = true
if (ctx.Request.Method == http.MethodPost || ctx.Request.Method == http.MethodPut || ctx.Request.Method == http.MethodPatch) &&
strings.Contains(ctx.Request.Header.Get("Content-Type"), "multipart/form-data") {
if err := ctx.Request.ParseMultipartForm(defaultMultipartMemory); err != nil {
panic(errors.New("parseMultipartForm error:" + err.Error()))
}
} else {
if err := ctx.Request.ParseForm(); err != nil {
panic(errors.New("parseForm error:" + err.Error()))
}
}
}