-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
112 lines (91 loc) · 2.23 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
package kin
import (
"encoding/json"
"fmt"
"net/http"
)
type AnyMap map[string]interface{}
type Context struct {
Writer http.ResponseWriter
Req *http.Request
Path string
Method string
StatusCode int
Params map[string]string
handles []HandleFunc
index int
engine *Engine
}
func NewContext(writer http.ResponseWriter, req *http.Request) *Context {
return &Context{
Writer: writer,
Req: req,
Path: req.URL.Path,
Method: req.Method,
handles: []HandleFunc{},
index: -1,
}
}
// 请求地址中获取参数
func (c *Context) Query(key string) string {
return c.Req.URL.Query().Get(key)
}
// 请求body中获取参数
func (c *Context) PostValue(key string) string {
return c.Req.FormValue(key)
}
// 打印所有body 参数
func (c *Context) AllPostValue() map[string][]string {
return c.Req.PostForm;
}
// 设置状态码
func (c *Context) SetStatus(code int) {
c.StatusCode = code
c.Writer.WriteHeader(code);
}
// 设置响应头
func (c *Context) SetHeader(key string, value string) {
c.Writer.Header().Set(key, value);
}
// JSON 格式的响应
func (c *Context) Json(code int, response interface{}) {
c.SetHeader("Content-Type", "application/json")
c.SetStatus(code)
encoder := json.NewEncoder(c.Writer)
if err := encoder.Encode(response); err != nil {
http.Error(c.Writer, err.Error(), 500)
}
}
// HTML 响应
func (c *Context) Html(code int, filename string, data AnyMap) {
c.SetStatus(code)
c.SetHeader("Content-Type", "text/html")
//c.Writer.Write([]byte(html))
if err := c.engine.templates.ExecuteTemplate(c.Writer, filename, data); err != nil {
c.Fail(http.StatusNotImplemented, err.Error())
}
}
// 数据响应
func (c *Context) Bytes(code int, data []byte) {
c.SetStatus(code)
c.Writer.Write(data);
}
// 字符串响应
func (c *Context) String(status int, format string, response...interface{}) {
c.SetHeader("Content-Type", "text/plain")
c.SetStatus(200)
c.Writer.Write([]byte(fmt.Sprintf(format, response...)))
}
// 洋葱顺序 执行中间件, 直至中间件栈 执行完毕
func (c *Context) Next() {
total := len(c.handles)
c.index++
for ; c.index < total; c.index++ {
c.handles[c.index](c)
}
}
func (c *Context) Fail(code int, err string) {
c.Json(code, AnyMap{
"message": err,
})
}