forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
93 lines (83 loc) · 2.04 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
package buffalo
import (
"context"
"net/http"
"sync"
"github.com/gobuffalo/buffalo/binding"
"github.com/gobuffalo/buffalo/render"
"github.com/gobuffalo/x/httpx"
"github.com/gorilla/mux"
)
// Context holds on to information as you
// pass it down through middleware, Handlers,
// templates, etc... It strives to make your
// life a happier one.
type Context interface {
context.Context
Response() http.ResponseWriter
Request() *http.Request
Session() *Session
Cookies() *Cookies
Params() ParamValues
Param(string) string
Set(string, interface{})
LogField(string, interface{})
LogFields(map[string]interface{})
Logger() Logger
Bind(interface{}) error
Render(int, render.Renderer) error
Error(int, error) error
Redirect(int, string, ...interface{}) error
Data() map[string]interface{}
Flash() *Flash
File(string) (binding.File, error)
}
// ParamValues will most commonly be url.Values,
// but isn't it great that you set your own? :)
type ParamValues interface {
Get(string) string
}
func (a *App) newContext(info RouteInfo, res http.ResponseWriter, req *http.Request) Context {
if ws, ok := res.(*Response); ok {
res = ws
}
params := req.URL.Query()
vars := mux.Vars(req)
for k, v := range vars {
params.Set(k, v)
}
if err := req.ParseForm(); err == nil {
for k, v := range req.Form {
for _, vv := range v {
params.Set(k, vv)
}
}
}
session := a.getSession(req, res)
ct := httpx.ContentType(req)
contextData := map[string]interface{}{
"app": a,
"env": a.Env,
"routes": a.Routes(),
"current_route": info,
"current_path": req.URL.Path,
"contentType": ct,
"method": req.Method,
}
for _, route := range a.Routes() {
cRoute := route
contextData[cRoute.PathName] = cRoute.BuildPathHelper()
}
return &DefaultContext{
Context: req.Context(),
contentType: ct,
response: res,
request: req,
params: params,
logger: a.Logger,
session: session,
flash: newFlash(session),
data: contextData,
moot: &sync.RWMutex{},
}
}