代码改变世界

Go Web开发之Revel - 概念

2012-12-28 15:58  Danny.tian  阅读(3194)  评论(0编辑  收藏  举报

MVC

摘要:

  • Model:用于描述你的应用程序域的基本数据对象,Model也包含特定领域的逻辑为了查询和更新数据
  • View:描述怎样展示和操作数据
  • Controller:处理请求的执行,他们执行用户期待的Action,他们决定哪个视图将被用于显示,他们还为视图准备和提供必要的数据用于渲染视图

每个请求产生一个Goroutine

  Revel构建于Go HTTP server之上,它为每一个进来的请求创建一个go-routine(轻量级线程),这意味着你的代码可以自由的阻塞,但必须处理并发请求处理。

Controllers and Actions

  每一个HTTP请求调用一个action,它处理请求和输出响应内容,相关联的action被分组到controller中。

  一个controller是任意嵌入rev.Controller的类型(直接或间接)

典型的Controller:

type AppController struct {
  *rev.Controller
}

(当前的rev.Controller必须作为这个struct的第一个类型被嵌入)

rev.Controller是请求的上下文,它包含request和response的数据。详情请参考godoc

type Controller struct {
    Name       string
    Type       *ControllerType
    MethodType *MethodType

    Request  *Request
    Response *Response

    Flash      Flash                  // User cookie, cleared after each request.
    Session    Session                // Session, stored in cookie, signed.
    Params     Params                 // Parameters from URL and form (including multipart).
    Args       map[string]interface{} // Per-request scratch space.
    RenderArgs map[string]interface{} // Args passed to the template.
    Validation *Validation            // Data validation helpers
    Txn        *sql.Tx                // Nil by default, but may be used by the app / plugins
}

// Flash represents a cookie that gets overwritten on each request.
// It allows data to be stored across one page at a time.
// This is commonly used to implement success or error messages.
// e.g. the Post/Redirect/Get pattern: http://en.wikipedia.org/wiki/Post/Redirect/Get
type Flash struct {
    Data, Out map[string]string
}

// These provide a unified view of the request params.
// Includes:
// - URL query string
// - Form values
// - File uploads
type Params struct {
    url.Values
    Files map[string][]*multipart.FileHeader
}

// A signed cookie (and thus limited to 4kb in size).
// Restriction: Keys may not have a colon in them.
type Session map[string]string

type Request struct {
    *http.Request
    ContentType string
}

type Response struct {
    Status      int
    ContentType string
    Headers     http.Header
    Cookies     []*http.Cookie

    Out http.ResponseWriter
}

作为处理HTTP请求的一部分,Revel实例化一个你Controller的实例,它设置全部的属性在rev.Controller上面,因此Revel不在请求之间共享Controller实例。

Action是Controller里面任意一个符合下面要求的方法:

  • 被导出的
  • 返回一个rev.Result

实例如下:

func (c AppController) ShowLogin(username string) rev.Result {
    ..
    return c.Render(username)
}

这个例子调用rev.Controller.Render来执行一个模板,将username作为参数传递,Controller中有许多方法产生rev.Result,但是应用程序也是自由的创建他们自己的Controller

Results

一个结果是任意符合接口的东东

type Result interface {
    Apply(req *Request, resp *Response)
}

没用任何东西被写入response,直到action 返回一个Result,此时Revel输出header和cookie,然后调用Result.Apply写入真正的输出内容.

(action可以选择直接输出内容,但是这只用于特殊情况下,在那些情况下它将必须自己处理保存Session和Flash数据).