Go Web開發之Revel - 概念


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數據).


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM