-
Notifications
You must be signed in to change notification settings - Fork 5
/
context.go
332 lines (280 loc) · 7.61 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
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
package goa
import (
"fmt"
"mime/multipart"
"net/http"
"net/url"
"github.com/goa-go/goa/parser"
"github.com/goa-go/goa/responser"
)
// Param is a single URL parameter, consisting of a key and a value.
type Param struct {
Key string
Value string
}
// Params is a Param-slice, as returned by the router.
// The slice is ordered, the first URL parameter is also the first slice value.
// It is therefore safe to read values by the index.
type Params []Param
// Context is used to receive requests and respond to requests.
type Context struct {
Request *http.Request
ResponseWriter http.ResponseWriter
Method string
URL *url.URL
Path string
Header http.Header
queryMap url.Values
Params Params
Keys map[string]interface{}
status int
explicitStatus bool
// Content-Type
ct string
// whether handled response by c.ResponseWriter
Handled bool
redirected bool
index int8
len int8
app *Goa
responser responser.Responser
}
func (c *Context) init(w http.ResponseWriter, r *http.Request) {
c.Request = r
c.ResponseWriter = w
c.Method = r.Method
c.URL = r.URL
c.Path = r.URL.Path
c.Header = r.Header
c.status = http.StatusNotFound
c.explicitStatus = false
c.Params = nil
c.Keys = nil
c.queryMap = nil
c.ct = ""
c.Handled = false
c.redirected = false
c.responser = nil
c.index = 0
c.len = int8(len(c.app.middlewares))
}
// Next implements the next middleware.
// For example,
// app.Use(func(c *goa.Context) {
// //do sth
// c.Next()
// //do sth
// })
func (c *Context) Next() {
if c.index >= c.len-1 {
return
}
c.index++
c.app.middlewares[c.index](c)
}
// Set value.
func (c *Context) Set(key string, value interface{}) {
if c.Keys == nil {
c.Keys = make(map[string]interface{})
}
c.Keys[key] = value
}
// Get value, return (value, exists).
func (c *Context) Get(key string) (value interface{}, exists bool) {
value, exists = c.Keys[key]
return
}
/* handle request */
// Query returns the keyed url query value or ""
func (c *Context) Query(key string) string {
query, _ := c.GetQuery(key)
return query
}
// GetQuery returns the keyed url query value and isExit
// if it exists, return (value, true)
// otherwise it returns ("", false)
func (c *Context) GetQuery(key string) (string, bool) {
if querys, ok := c.GetQueryArray(key); ok {
return querys[0], true
}
return "", false
}
// GetQueryArray returns a slice of value for a given query key.
// And returns whether at least one value exists for the given key.
func (c *Context) GetQueryArray(key string) ([]string, bool) {
c.initQuery()
if querys, ok := c.queryMap[key]; ok && len(querys) > 0 {
return querys, true
}
return []string{}, false
}
func (c *Context) initQuery() {
if c.queryMap == nil {
c.queryMap = make(url.Values)
c.queryMap, _ = url.ParseQuery(c.Request.URL.RawQuery)
}
}
// PostForm returns the value from a POST form or "".
func (c *Context) PostForm(key string) string {
return c.Request.PostFormValue(key)
}
// FormFile returns the first file for the provided form key.
func (c *Context) FormFile(name string) (multipart.File, *multipart.FileHeader, error) {
return c.Request.FormFile(name)
}
// Param returns the value of the URL param or "".
// When using goa-router, it works.
func (c *Context) Param(key string) string {
return c.Params.Get(key)
}
// Get returns the value of the first Param which key matches the given name.
// If no matching Param is found, an empty string is returned.
func (ps Params) Get(name string) string {
for _, param := range ps {
if param.Key == name {
return param.Value
}
}
return ""
}
func (c *Context) parse(p parser.Parser) error {
return p.Parse(c.Request)
}
// ParseJSON parses json-data, require a pointer.
func (c *Context) ParseJSON(pointer interface{}) error {
return c.parse(parser.JSON{Pointer: pointer})
}
// ParseXML parses xml-data, require a pointer.
func (c *Context) ParseXML(pointer interface{}) error {
return c.parse(parser.XML{Pointer: pointer})
}
// ParseString returns string-data
func (c *Context) ParseString() (string, error) {
return parser.String{}.Parse(c.Request)
}
// ParseQuery can parse query, require a pointer.
// Just like json, it also needs a "query" tag. Here is a example.
//
// type Person struct {
// Name string `query:"name"`
// Age int `query:"age"`
// }
//
// p := &Person{}
// c.ParseQuery(p)
func (c *Context) ParseQuery(pointer interface{}) error {
return c.parse(parser.Query{Pointer: pointer})
}
// ParseForm can parse form-data and x-www-form-urlencoded,
// the latter is not available when the request method is get,
// require a pointer.
// Just like json, it also needs a "form" tag. Here is a example.
//
// type Person struct {
// Name string `form:"name"`
// Age int `form:"age"`
// }
//
// p := &Person{}
// c.ParseForm(p)
func (c *Context) ParseForm(pointer interface{}) error {
return c.parse(parser.Form{Pointer: pointer})
}
// Cookie returns the named cookie provided in the request
// or ErrNoCookie if not found.
func (c *Context) Cookie(name string) (string, error) {
cookie, err := c.Request.Cookie(name)
if err != nil {
return "", err
}
val, _ := url.QueryUnescape(cookie.Value)
return val, nil
}
/* handle response */
// Status sets the HTTP response code.
func (c *Context) Status(code int) {
if code < 100 || code > 999 {
panic(fmt.Errorf("invalid status code: %d", code))
}
c.explicitStatus = true
c.status = code
}
// GetStatus returns c.status.
func (c *Context) GetStatus() int {
return c.status
}
// M is a convenient alias for a map[string]interface{} map.
// Use is as c.JSON(&goa.M{...})
type M map[string]interface{}
func (c *Context) respond(r responser.Responser) error {
return r.Respond(c.ResponseWriter)
}
// JSON responds json-data.
func (c *Context) JSON(json interface{}) {
if !c.explicitStatus {
c.Status(http.StatusOK)
}
c.ct = "application/json; charset=utf-8"
c.responser = responser.JSON{Data: json}
}
// XML responds xml-data.
func (c *Context) XML(xml interface{}) {
if !c.explicitStatus {
c.Status(http.StatusOK)
}
c.ct = "application/xml; charset=utf-8"
c.responser = responser.XML{Data: xml}
}
// String responds string-data.
func (c *Context) String(str string) {
if !c.explicitStatus {
c.Status(http.StatusOK)
}
c.ct = "text/plain; charset=utf-8"
c.responser = responser.String{Data: str}
}
// HTML responds html.
func (c *Context) HTML(html string) {
if !c.explicitStatus {
c.Status(http.StatusOK)
}
c.ct = "text/html; charset=utf-8"
c.responser = responser.String{Data: html}
}
// Redirect replies to the request with a redirect to url and a status code.
func (c *Context) Redirect(code int, url string) {
if code < http.StatusMultipleChoices || code > http.StatusPermanentRedirect {
panic(fmt.Errorf("cannot redirect with status code %d", code))
}
c.redirected = true
c.Status(code)
http.Redirect(c.ResponseWriter, c.Request, url, code)
}
// SetHeader sets http response header.
// It should be called before Status and Respond.
func (c *Context) SetHeader(key string, value string) {
c.ResponseWriter.Header().Set(key, value)
}
func (c *Context) writeContentType(value string) {
header := c.ResponseWriter.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = []string{value}
}
}
// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
func (c *Context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.ResponseWriter, cookie)
}
// Error is used like c.Error(goa.Error{...}).
// It will create a http-error.
type Error struct {
Code int
Msg string
}
// Error throw a http-error, it would be catched by goa.
func (c *Context) Error(code int, msg string) {
panic(Error{
code,
msg,
})
}