This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 577
/
context.go
99 lines (86 loc) · 2.25 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
package buffalo
import (
"context"
"net/http"
"net/url"
"sync"
"github.com/gobuffalo/buffalo/binding"
"github.com/gobuffalo/buffalo/internal/httpx"
"github.com/gobuffalo/buffalo/render"
"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
}
// Parse URL Params
params := url.Values{}
vars := mux.Vars(req)
for k, v := range vars {
params.Add(k, v)
}
// Parse URL Query String Params
// For POST, PUT, and PATCH requests, it also parse the request body as a form.
// Request body parameters take precedence over URL query string values in params
if err := req.ParseForm(); err == nil {
for k, v := range req.Form {
for _, vv := range v {
params.Add(k, vv)
}
}
}
session := a.getSession(req, res)
ct := httpx.ContentType(req)
data := &sync.Map{}
data.Store("app", a)
data.Store("env", a.Env)
data.Store("routes", a.Routes())
data.Store("current_route", info)
data.Store("current_path", req.URL.Path)
data.Store("contentType", ct)
data.Store("method", req.Method)
for _, route := range a.Routes() {
cRoute := route
data.Store(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: data,
}
}