This repository has been archived by the owner on Sep 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default_context.go
235 lines (204 loc) · 6.42 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
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
package buffalo
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"runtime"
"sort"
"strings"
"time"
"github.com/gobuffalo/buffalo/binding"
"github.com/gobuffalo/buffalo/render"
"github.com/gobuffalo/pop"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
// assert that DefaultContext is implementing Context
var _ Context = &DefaultContext{}
var _ context.Context = &DefaultContext{}
// DefaultContext is, as its name implies, a default
// implementation of the Context interface.
type DefaultContext struct {
context.Context
response http.ResponseWriter
request *http.Request
params url.Values
logger Logger
session *Session
contentType string
data map[string]interface{}
flash *Flash
}
// 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.
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)
}
// 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
}
// Value that has previously stored on the context.
func (d *DefaultContext) Value(key interface{}) interface{} {
if k, ok := key.(string); ok {
if v, ok := d.data[k]; ok {
return v
}
}
return d.Context.Value(key)
}
// Session for the associated Request.
func (d *DefaultContext) Session() *Session {
return d.session
}
// Cookies for the associated request and response.
func (d *DefaultContext) Cookies() *Cookies {
return &Cookies{d.request, d.response}
}
// Flash messages for the associated Request.
func (d *DefaultContext) Flash() *Flash {
return d.flash
}
// 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 {
start := time.Now()
defer func() {
d.LogField("render", time.Since(start))
}()
if rr != nil {
data := d.data
pp := map[string]string{}
for k, v := range d.params {
pp[k] = v[0]
}
data["params"] = pp
data["flash"] = d.Flash().data
data["session"] = d.Session()
data["request"] = d.Request()
data["status"] = status
bb := &bytes.Buffer{}
err := rr.Render(bb, data)
if err != nil {
if er, ok := errors.Cause(err).(render.ErrRedirect); ok {
return d.Redirect(er.Status, er.URL)
}
return HTTPError{Status: 500, Cause: errors.WithStack(err)}
}
if d.Session() != nil {
d.Flash().Clear()
d.Flash().persist(d.Session())
}
d.Response().Header().Set("Content-Type", rr.ContentType())
if p, ok := data["pagination"].(*pop.Paginator); ok {
d.Response().Header().Set("X-Pagination", p.String())
}
d.Response().WriteHeader(status)
_, err = io.Copy(d.Response(), bb)
if err != nil {
return HTTPError{Status: 500, Cause: errors.WithStack(err)}
}
return nil
}
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". See the
// github.com/gobuffalo/buffalo/binding package for more details.
func (d *DefaultContext) Bind(value interface{}) error {
return binding.Exec(d.Request(), value)
}
// 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 {
return HTTPError{Status: status, Cause: errors.WithStack(err)}
}
// Websocket is deprecated, and will be removed in v0.12.0. Use github.com/gorilla/websocket directly instead.
func (d *DefaultContext) Websocket() (*websocket.Conn, error) {
warningMsg := "Websocket is deprecated, and will be removed in v0.12.0. Use github.com/gorilla/websocket directly instead."
_, file, no, ok := runtime.Caller(1)
if ok {
warningMsg = fmt.Sprintf("%s Called from %s:%d", warningMsg, file, no)
}
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 {
d.Flash().persist(d.Session())
if len(args) > 0 {
url = fmt.Sprintf(url, args...)
}
http.Redirect(d.Response(), d.Request(), url, status)
return nil
}
// Data contains all the values set through Get/Set.
func (d *DefaultContext) Data() map[string]interface{} {
return d.data
}
func (d *DefaultContext) String() string {
bb := make([]string, 0, len(d.data))
for k, v := range d.data {
if _, ok := v.(RouteHelperFunc); !ok {
bb = append(bb, fmt.Sprintf("%s: %s", k, v))
}
}
sort.Strings(bb)
return strings.Join(bb, "\n\n")
}
// File returns an uploaded file by name, or an error
func (d *DefaultContext) File(name string) (binding.File, error) {
req := d.Request()
if err := req.ParseMultipartForm(5 * 1024 * 1024); err != nil {
return binding.File{}, err
}
f, h, err := req.FormFile(name)
bf := binding.File{
File: f,
FileHeader: h,
}
if err != nil {
return bf, errors.WithStack(err)
}
return bf, nil
}
var defaultUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}