-
Notifications
You must be signed in to change notification settings - Fork 5
/
ctx.go
125 lines (103 loc) · 2.33 KB
/
ctx.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
package quick
import (
"encoding/json"
"encoding/xml"
"net/http"
"strings"
)
type Ctx struct {
Response http.ResponseWriter
Request *http.Request
resStatus int
MoreRequests int
bodyByte []byte
JsonStr string
Headers map[string][]string
Params map[string]string
Query map[string]string
}
func (c *Ctx) Bind(v interface{}) (err error) {
return extractBind(c, v)
}
func (c *Ctx) BodyParser(v interface{}) (err error) {
if strings.Contains(c.Request.Header.Get("Content-Type"), ContentTypeAppJSON) {
err = json.Unmarshal(c.bodyByte, v)
if err != nil {
return err
}
}
if strings.Contains(c.Request.Header.Get("Content-Type"), ContentTypeTextXML) ||
strings.Contains(c.Request.Header.Get("Content-Type"), ContentTypeAppXML) {
err = xml.Unmarshal(c.bodyByte, v)
if err != nil {
return err
}
}
return nil
}
func (c *Ctx) Param(key string) string {
val, ok := c.Params[key]
if ok {
return val
}
return ""
}
func (c *Ctx) Body() []byte {
return c.bodyByte
}
func (c *Ctx) BodyString() string {
return string(c.bodyByte)
}
func (c *Ctx) JSON(v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
c.Response.Header().Set("Content-Type", ContentTypeAppJSON)
return c.writeResponse(b)
}
func (c *Ctx) XML(v interface{}) error {
b, err := xml.Marshal(v)
if err != nil {
return err
}
c.Response.Header().Set("Content-Type", ContentTypeTextXML)
return c.writeResponse(b)
}
func (c *Ctx) writeResponse(b []byte) error {
if c.resStatus != 0 {
c.Response.WriteHeader(c.resStatus)
}
_, err := c.Response.Write(b)
return err
}
func (c *Ctx) Byte(b []byte) (err error) {
return c.writeResponse(b)
}
func (c *Ctx) Send(b []byte) (err error) {
return c.writeResponse(b)
}
func (c *Ctx) SendString(s string) error {
return c.writeResponse([]byte(s))
}
func (c *Ctx) String(s string) error {
return c.writeResponse([]byte(s))
}
func (c *Ctx) SendFile(file []byte) error {
_, err := c.Response.Write(file)
return err
}
func (c *Ctx) Set(key, value string) {
c.Response.Header().Set(key, value)
}
func (c *Ctx) Append(key, value string) {
c.Response.Header().Add(key, value)
}
func (c *Ctx) Accepts(acceptType string) *Ctx {
c.Response.Header().Set("Accept", acceptType)
return c
}
func (c *Ctx) Status(status int) *Ctx {
c.resStatus = status
return c
}