上下文
每个Buffalo请求处理程序的核心是Context
。上下文为处理程序提供了一个简单,干净、功能强大的函数定义。
buffalo.Context 继承自context.Context,所以它也是一个go语言中标准的上下文。
由于buffalo.Context是一个接口,因此需要在应用中根据应用的需要,构建具体的实现。
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)
}
说明:从v0.12.0版本之后,Websocket() (*websocket.Conn, error)被移除了。如果需要可以使用www.gorillatoolkit.org/pkg/websocke...代替。
上下文和渲染
作为上下文接口的一部分,这里的Render函数接受render.Renderer,具体可以参考渲染章节。
在上下文中“Set”的任何值将自动可用于render.Renderer
传递给Render
函数的值。相当于beego中的Data。
func Hello(c buffalo.Context) error {
c.Set("name", "Mark")
return c.Render(200, render.String("Hi <%= name %>"))
}
实现接口
buffalo.Context不是万能,不能满足我们全部需求,有时候我们需要在其基础上扩展一些属性或者功能
下面是更改Error
函数以记录错误和终止应用程序的示例
// actions/context.go
type MyContext struct {
buffalo.Context
}
func (my MyContext) Error(status int, err error) error {
my.Logger().Fatal(err)
return err
}
// actions/app.go
// ...
func App() *buffalo.App {
if app != nil {
// ...
app.Use(func (next buffalo.Handler) buffalo.Handler {
return func(c buffalo.Context) error {
// change the context to MyContext
return next(MyContext{c})
}
})
// ...
}
return app
}
// ...
范围参数
The buffalo.Context#Params
method returns buffalo.ParamValues
which is an interface around url.Values
. 您可以在处理程序中强制转换为此类型,以覆盖参数值
func HomeHandler(c buffalo.Context) error {
if m, ok := c.Params().(url.Values); ok {
for k, v := range m {
fmt.Println(k, v)
}
}
return c.Render(200, r.HTML("index.html"))
}
上下文中的内容
Buffalo会在每个请求的上下文中填充大量可能对您的应用程序有用的信息,例如current_route
或者session
。下面是我们在操作或模板中可以访问的每个请求中上下文的列表。
Key | Type | Usage |
---|---|---|
app | *buffalo.App | 当前正在运行的Buffalo应用程序. |
env | string | The current environment the app is running in. Example: test , development , production |
routes | buffalo.RouteList | 应用程序上映射的所有路由的列表 |
current_route | buffalo.RouteInfo | 正在访问的当前路由 |
current_path | string | The current path being requested. Example: /users/1/edit |
*Path | RouteHelperFunc | Helpers to create paths based off of mapped routes. Example: editUserPath . Run buffalo task routes to see a full list for your app. |
params | map[string]string | 请求页面的查询参数. |
flash | map[string][]string | A map of messages set using buffalo.Context#Flash . |
session | *buffalo.Session | The current user’s session. |
request | *http.Request | The current request. |
tx | *pop.Connection | Only set if using the github.com/gobuffalo/buffalo/middleware.PopTransaction middleware (on by default). |
模板内可用的内置帮助程序函数的列表,请参阅助手章节