forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default_context.go
187 lines (165 loc) · 5.55 KB
/
default_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
package buffalo
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gorilla/schema"
"github.com/gorilla/websocket"
"github.com/gobuffalo/buffalo/render"
"github.com/pkg/errors"
)
// DefaultContext is, as its name implies, a default
// implementation of the Context interface.
type DefaultContext struct {
response http.ResponseWriter
request *http.Request
params url.Values
logger Logger
session *Session
contentType string
data map[string]interface{}
}
// Response returns the original Response for the request.
func (d *DefaultContext) Response() http.ResponseWriter {
return d.response
}
// Request returns the original Request.
func (d *DefaultContext) Request() *http.Request {
return d.request
}
// Params returns all of the parameters for the request,
// including both named params and query string parameters.
// These parameters are automatically available in templates
// as "{{.params}}".
func (d *DefaultContext) Params() ParamValues {
return d.params
}
// Logger returns the Logger for this context.
func (d *DefaultContext) Logger() Logger {
return d.logger
}
// Param returns a param, either named or query string,
// based on the key.
func (d *DefaultContext) Param(key string) string {
return d.Params().Get(key)
}
// ParamInt tries to convert the requested parameter to
// an int. It will return an error if there is a problem.
func (d *DefaultContext) ParamInt(key string) (int, error) {
k := d.Params().Get(key)
i, err := strconv.Atoi(k)
return i, errors.WithMessage(err, fmt.Sprintf("could not convert %s to an int", k))
}
// Set a value onto the Context. Any value set onto the Context
// will be automatically available in templates.
func (d *DefaultContext) Set(key string, value interface{}) {
d.data[key] = value
}
// Get a value that was previous set onto the Context.
func (d *DefaultContext) Get(key string) interface{} {
return d.data[key]
}
// Session for the associated Request.
func (d *DefaultContext) Session() *Session {
return d.session
}
// Render a status code and render.Renderer to the associated Response.
// The request parameters will be made available to the render.Renderer
// "{{.params}}". Any values set onto the Context will also automatically
// be made available to the render.Renderer. To render "no content" pass
// in a nil render.Renderer.
func (d *DefaultContext) Render(status int, rr render.Renderer) error {
now := time.Now()
defer func() {
d.LogField("render", time.Now().Sub(now))
}()
if rr != nil {
d.Response().Header().Set("Content-Type", rr.ContentType())
d.Response().WriteHeader(status)
data := d.data
pp := map[string]string{}
for k, v := range d.params {
pp[k] = v[0]
}
data["params"] = pp
return rr.Render(d.Response(), data)
}
d.Response().WriteHeader(status)
return nil
}
// Bind the interface to the request.Body. The type of binding
// is dependent on the "Content-Type" for the request. If the type
// is "application/json" it will use "json.NewDecoder". If the type
// is "application/xml" it will use "xml.NewDecoder". The default
// binder is "http://www.gorillatoolkit.org/pkg/schema".
func (d *DefaultContext) Bind(value interface{}) error {
switch strings.ToLower(d.Request().Header.Get("Content-Type")) {
case "application/json", "text/json", "json":
return json.NewDecoder(d.Request().Body).Decode(value)
case "application/xml", "text/xml", "xml":
return xml.NewDecoder(d.Request().Body).Decode(value)
default:
err := d.Request().ParseForm()
if err != nil {
return err
}
dec := schema.NewDecoder()
dec.IgnoreUnknownKeys(true)
dec.ZeroEmpty(true)
return dec.Decode(value, d.Request().PostForm)
}
}
// LogField adds the key/value pair onto the Logger to be printed out
// as part of the request logging. This allows you to easily add things
// like metrics (think DB times) to your request.
func (d *DefaultContext) LogField(key string, value interface{}) {
d.logger = d.logger.WithField(key, value)
}
// LogFields adds the key/value pairs onto the Logger to be printed out
// as part of the request logging. This allows you to easily add things
// like metrics (think DB times) to your request.
func (d *DefaultContext) LogFields(values map[string]interface{}) {
d.logger = d.logger.WithFields(values)
}
func (d *DefaultContext) Error(status int, err error) error {
err = errors.WithStack(err)
d.Logger().Error(err)
msg := fmt.Sprintf("%+v", err)
d.Response().WriteHeader(status)
ct := d.Request().Header.Get("Content-Type")
switch strings.ToLower(ct) {
case "application/json", "text/json", "json":
err = json.NewEncoder(d.Response()).Encode(map[string]interface{}{
"error": msg,
"code": status,
})
case "application/xml", "text/xml", "xml":
default:
_, err = d.Response().Write([]byte(msg))
}
return err
}
// Websocket returns an upgraded github.com/gorilla/websocket.Conn
// that can then be used to work with websockets easily.
func (d *DefaultContext) Websocket() (*websocket.Conn, error) {
return defaultUpgrader.Upgrade(d.Response(), d.Request(), nil)
}
// Redirect a request with the given status to the given URL.
func (d *DefaultContext) Redirect(status int, url string, args ...interface{}) error {
http.Redirect(d.Response(), d.Request(), fmt.Sprintf(url, args...), status)
return nil
}
// Data contains all the values set through Get/Set.
func (d *DefaultContext) Data() map[string]interface{} {
return d.data
}
var defaultUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}