forked from gramework/gramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
254 lines (220 loc) · 6.63 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
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
package gramework
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"strings"
acceptParser "github.com/kirillDanshin/go-accept-headers"
"github.com/valyala/fasthttp"
)
// Writef is a fmt.Fprintf(context, format, a...) shortcut
func (ctx *Context) Writef(format string, a ...interface{}) {
fmt.Fprintf(ctx, format, a...)
}
// Writeln is a fmt.Fprintln(context, format, a...) shortcut
func (ctx *Context) Writeln(a ...interface{}) {
fmt.Fprintln(ctx, a...)
}
// RouteArg returns an argument value as a string or empty string
func (ctx *Context) RouteArg(argName string) string {
v, err := ctx.RouteArgErr(argName)
if err != nil {
return emptyString
}
return v
}
// @TODO: add more
var ctypes = []string{
jsonCT,
xmlCT,
}
// Encode automatically determies accepted formats
// and choose preferred one
func (ctx *Context) Encode(v interface{}) (sentType string, err error) {
accept := ctx.Request.Header.Peek(acceptHeader)
accepted := acceptParser.Parse(BytesToString(accept))
sentType, err = accepted.Negotiate(ctypes...)
if err != nil {
return
}
switch sentType {
case jsonCT:
ctx.JSON(v)
case xmlCT:
ctx.XML(v)
}
return
}
// XML sends text/xml content type (see rfc3023, sec 3) and xml-encoded value to client
func (ctx *Context) XML(v interface{}) error {
ctx.SetContentType(xmlCT)
b, err := ctx.ToXML(v)
if err != nil {
return err
}
ctx.Write(b)
return nil
}
// ToXML encodes xml-encoded value to client
func (ctx *Context) ToXML(v interface{}) ([]byte, error) {
b := bytes.NewBuffer(nil)
err := xml.NewEncoder(b).Encode(v)
return b.Bytes(), err
}
// GETKeys returns GET parameters keys
func (ctx *Context) GETKeys() []string {
res := []string{}
ctx.Request.URI().QueryArgs().VisitAll(func(key, value []byte) {
res = append(res, string(key))
})
return res
}
// GETKeysBytes returns GET parameters keys as []byte
func (ctx *Context) GETKeysBytes() [][]byte {
res := [][]byte{}
ctx.Request.URI().QueryArgs().VisitAll(func(key, value []byte) {
res = append(res, key)
})
return res
}
// GETParams returns GET parameters
func (ctx *Context) GETParams() map[string][]string {
res := map[string][]string{}
ctx.Request.URI().QueryArgs().VisitAll(func(key, value []byte) {
res[string(key)] = append(res[string(key)], string(value))
})
return res
}
// GETParam returns GET parameter by name
func (ctx *Context) GETParam(argName string) []string {
res := ctx.GETParams()
if param, ok := res[argName]; ok {
return param
}
return []string{}
}
// RouteArgErr returns an argument value as a string or empty string
// and ErrArgNotFound if argument was not found
func (ctx *Context) RouteArgErr(argName string) (string, error) {
i := ctx.UserValue(argName)
if i == nil {
return emptyString, ErrArgNotFound
}
switch value := i.(type) {
case string:
return value, nil
default:
return fmt.Sprintf(fmtV, i), nil
}
}
// HTML sets HTML content type
func (ctx *Context) HTML() *Context {
ctx.SetContentType(htmlCT)
return ctx
}
// ToTLS redirects user to HTTPS scheme
func (ctx *Context) ToTLS() {
u := ctx.URI()
u.SetScheme(https)
ctx.Redirect(u.String(), redirectCode)
}
const (
redirectCode = 301
temporaryRedirectCode = 307
zero = 0
one = 1
https = "https"
corsAccessControlAllowOrigin = "Access-Control-Allow-Origin"
corsAccessControlAllowMethods = "Access-Control-Allow-Methods"
corsAccessControlAllowHeaders = "Access-Control-Allow-Headers"
corsAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
methods = "GET,PUT,POST,DELETE"
corsCType = "Content-Type, *"
trueStr = "true"
jsonCT = "application/json;charset=utf8"
hOrigin = "Origin"
forbidden = "Forbidden"
forbiddenCode = 403
)
// CORS enables CORS in the current context
func (ctx *Context) CORS(domains ...string) *Context {
origins := make([]string, 0)
if len(domains) > 0 {
origins = domains
} else if headerOrigin := ctx.Request.Header.Peek(hOrigin); headerOrigin != nil && len(headerOrigin) > 0 {
origins = append(origins, string(headerOrigin))
} else {
origins = append(origins, string(ctx.Request.URI().Host()))
}
ctx.Response.Header.Set(corsAccessControlAllowOrigin, strings.Join(origins, " "))
ctx.Response.Header.Set(corsAccessControlAllowMethods, methods)
ctx.Response.Header.Set(corsAccessControlAllowHeaders, corsCType)
ctx.Response.Header.Set(corsAccessControlAllowCredentials, trueStr)
return ctx
}
// Forbidden send 403 Forbidden error
func (ctx *Context) Forbidden() {
ctx.Error(forbidden, forbiddenCode)
}
// JSON serializes and writes a json-formatted response to user
func (ctx *Context) JSON(v interface{}) error {
ctx.SetContentType(jsonCT)
b, err := ctx.ToJSON(v)
ctx.Write(b)
return err
}
// ToJSON serializes and returns the result
func (ctx *Context) ToJSON(v interface{}) ([]byte, error) {
b := bytes.NewBuffer(nil)
err := json.NewEncoder(b).Encode(v)
return b.Bytes(), err
}
// UnJSONBytes serializes and writes a json-formatted response to user
func (ctx *Context) UnJSONBytes(b []byte, v ...interface{}) (interface{}, error) {
return UnJSONBytes(b, v...)
}
// UnJSON deserializes JSON request body to given variable pointer
func (ctx *Context) UnJSON(v interface{}) error {
return json.NewDecoder(bytes.NewReader(ctx.Request.Body())).Decode(&v)
}
// UnJSONBytes deserializes JSON request body to given variable pointer or allocates a new one.
// Returns resulting data and error. One of them may be nil.
func UnJSONBytes(b []byte, v ...interface{}) (interface{}, error) {
if len(v) == 0 {
var res interface{}
err := json.NewDecoder(bytes.NewReader(b)).Decode(&res)
return res, err
}
err := json.NewDecoder(bytes.NewReader(b)).Decode(&v[0])
return v[0], err
}
const badRequest = "Bad Request"
// BadRequest sends HTTP/1.1 400 Bad Request
func (ctx *Context) BadRequest(err ...error) {
ctx.Error(badRequest, fasthttp.StatusBadRequest)
if len(err) == 1 {
ctx.Writeln(err[0])
}
}
// Err500 sets Internal Server Error status
func (ctx *Context) Err500(message ...interface{}) *Context {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
for k := range message {
switch v := message[k].(type) {
case string:
ctx.WriteString(v)
case error:
ctx.Writef("%s", v)
default:
ctx.Writef("%v", v)
}
}
return ctx
}
// JSONError sets Internal Server Error status,
// serializes and writes a json-formatted response to user
func (ctx *Context) JSONError(v interface{}) error {
ctx.Err500()
return ctx.JSON(v)
}