上下文

未匹配的标注

每个 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.PopTransactionmiddleware (on by default).

模板内可用的内置帮助程序函数的列表,请参阅助手章节

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
superwen
贡献者:1
讨论数量: 0
发起讨论 查看所有版本


暂无话题~