/
context.go
105 lines (88 loc) · 2.06 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
package lates
import (
"io"
"mime/multipart"
"net"
"net/http"
"os"
"github.com/julienschmidt/httprouter"
)
type Context struct {
r *http.Request
p httprouter.Params
w http.ResponseWriter
}
func (c *Context) GetFormFile(key string) (multipart.File, *multipart.FileHeader, error) {
return c.r.FormFile(key)
}
func (c *Context) GetMultipartFile(name string, maxMemoryBytes int64) ([]*multipart.FileHeader, error) {
if c.r.MultipartForm == nil {
err := c.r.ParseMultipartForm(maxMemoryBytes)
if err != nil {
return nil, err
}
}
return c.r.MultipartForm.File[name], nil
}
func (c *Context) SaveFile(name, path string) error {
file, _, err := c.r.FormFile(name)
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, file)
return err
}
func (c *Context) SaveMultipartFile(name string, maxMemoryBytes int64, path string) error {
headers, err := c.GetMultipartFile(name, maxMemoryBytes)
if err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
for _, header := range headers {
file, err := header.Open()
if err != nil {
return err
}
defer file.Close()
if _, err := io.Copy(f, file); err != nil {
return err
}
}
return nil
}
func (c *Context) GetFormData(key string) string {
return c.r.FormValue(key)
}
func (c *Context) GetURLQuery(key string) string {
return c.r.URL.Query().Get(key)
}
func (c *Context) GetPathVariable(key string) string {
return c.p.ByName(key)
}
func (c *Context) GetBody() ([]byte, error) {
return io.ReadAll(c.r.Body)
}
func (c *Context) GetBodyReader() io.ReadCloser {
return c.r.Body
}
func (c *Context) GetCookie(key string) string {
return c.r.Header.Get("Cookie")
}
func (c *Context) GetRemoteAddress() string {
return c.r.RemoteAddr
}
func (c *Context) GetRemoteIpPort() (string, string, error) {
return net.SplitHostPort(c.r.RemoteAddr)
}
func (c *Context) SetStatusCode(statusCode int) {
c.w.WriteHeader(statusCode)
}
func (c *Context) Redirect(url string, statusCode int) {
http.Redirect(c.w, c.r, url, statusCode)
}