天天看點

beego架構學習(二) -路由設定

路由設定

什麼是路由設定呢?前面介紹的 MVC 結構執行時,介紹過 beego 存在三種方式的路由:固定路由、正則路由、自動路由,接下來詳細的講解如何使用這三種路由。 

基礎路由

從beego1.2版本開始支援了基本的RESTful函數式路由,應用中的大多數路由都會定義在 routers/router.go 檔案中。最簡單的beego路由由URI和閉包函數組成。 

基本 GET 路由

1

2

3

4

5

<code>beego.Get(</code><code>"/"</code><code>,</code><code>func</code><code>(ctx *context.Context){</code>

<code>         </code><code>ctx.Output.Body([]byte(</code><code>"hello world"</code><code>))</code>

<code>    </code><code>})</code>

  

基本 POST 路由

<code>beego.Post(</code><code>"/alice"</code><code>,</code><code>func</code><code>(ctx *context.Context){</code>

<code>         </code><code>ctx.Output.Body([]byte(</code><code>"bob"</code><code>))</code>

注冊一個可以響應任何HTTP的路由

<code>beego.Any(</code><code>"/foo"</code><code>,</code><code>func</code><code>(ctx *context.Context){</code>

<code>         </code><code>ctx.Output.Body([]byte(</code><code>"bar"</code><code>))</code>

所有的支援的基礎函數如下所示

6

7

8

9

10

11

12

13

<code>beego.Get(router, beego.FilterFunc)</code>

<code>   </code><code>beego.Post(router, beego.FilterFunc)</code>

<code>   </code><code>beego.Put(router, beego.FilterFunc)</code>

<code>   </code><code>beego.Head(router, beego.FilterFunc)</code>

<code>   </code><code>beego.Options(router, beego.FilterFunc)</code>

<code>   </code><code>beego.Delete(router, beego.FilterFunc)</code>

<code>   </code><code>beego.Any(router, beego.FilterFunc)</code>

支援自定義的handler實作

有些時候我們已經實作了一些rpc的應用,但是想要內建到beego中,或者其他的httpserver應用,內建到beego中來.現在可以很友善的內建:

<code>s := rpc.NewServer()</code>

<code>    </code><code>s.RegisterCodec(json.NewCodec(), </code><code>"application/json"</code><code>)</code>

<code>    </code><code>s.RegisterService(new(HelloService), </code><code>""</code><code>)</code>

<code>    </code><code>beego.Handler(</code><code>"/rpc"</code><code>, s)</code>

beego.Handler(router, http.Handler)這個函數是關鍵,第一個參數表示路由URI,第二個就是你自己實作的http.Handler,注冊之後就會把所有rpc作為字首的請求分發到http.Handler中進行處理.

這個函數其實還有第三個參數就是是否是字首比對,預設是false, 如果設定了true,那麼就會在路由比對的時候字首比對,即/rpc/user這樣的也會比對去運作路由參數

後面會講到固定路由,正則路由,這些參數一樣适用于上面的這些函數 

RESTful Controller 路由

在介紹這三種 beego 的路由實作之前先介紹 RESTful,我們知道 RESTful 是一種目前 API 開發中廣泛采用的形式,beego 預設就是支援這樣的請求方法,也就是使用者 Get 請求就執行 Get 方法,Post 請求就執行 Post 方法。是以預設的路由是這樣 RESTful 的請求方式。 

固定路由

固定路由也就是全比對的路由,如下所示:

<code>beego.Router(</code><code>"/"</code><code>, &amp;controllers.MainController{})</code>

<code>beego.Router(</code><code>"/admin"</code><code>, &amp;admin.UserController{})</code>

<code>beego.Router(</code><code>"/admin/index"</code><code>, &amp;admin.ArticleController{})</code>

<code>beego.Router(</code><code>"/admin/addpkg"</code><code>, &amp;admin.AddController{})</code>

如上所示的路由就是我們最常用的路由方式,一個固定的路由,一個控制器,然後根據使用者請求方法不同請求控制器中對應的方法,典型的 RESTful 方式。 

正則路由

為了使用者更加友善的路由設定,beego 參考了 sinatra 的路由實作,支援多種方式的路由:

 beego.Router(“/api/?:id”, &amp;controllers.RController{})

    預設比對 //比對 /api/123 :id = 123 可以比對/api/這個URL

    beego.Router(“/api/:id”, &amp;controllers.RController{})

    預設比對 //比對 /api/123 :id = 123 不可以比對/api/這個URL

    beego.Router(“/api/:id([0-9]+)“, &amp;controllers.RController{})

    自定義正則比對 //比對 /api/123 :id = 123

    beego.Router(“/user/:username([\w]+)“, &amp;controllers.RController{})

    正則字元串比對 //比對 /user/astaxie :username = astaxie

    beego.Router(“/download/*.*”, &amp;controllers.RController{})

    *比對方式 //比對 /download/file/api.xml :path= file/api :ext=xml

    beego.Router(“/download/ceshi/*“, &amp;controllers.RController{})

    *全比對方式 //比對 /download/ceshi/file/api.json :splat=file/api.json

    beego.Router(“/:id:int”, &amp;controllers.RController{})

    int 類型設定方式,比對 :id為int類型,架構幫你實作了正則([0-9]+)

    beego.Router(“/:hi:string”, &amp;controllers.RController{})

    string 類型設定方式,比對 :hi為string類型。架構幫你實作了正則([\w]+)

    beego.Router(“/cms_:id([0-9]+).html”, &amp;controllers.CmsController{})

    帶有字首的自定義正則 //比對 :id為正則類型。比對 cms_123.html這樣的url :id = 123

可以在 Controller 中通過如下方式擷取上面的變量:

this.Ctx.Input.Param(":id")

    this.Ctx.Input.Param(":username")

    this.Ctx.Input.Param(":splat")

    this.Ctx.Input.Param(":path")

    this.Ctx.Input.Param(":ext")

自定義方法及 RESTful 規則

上面列舉的是預設的請求方法名(請求的 method 和函數名一緻,例如 GET 請求執行 Get 函數,POST 請求執行 Post 函數),如果使用者期望自定義函數名,那麼可以使用如下方式:

beego.Router("/",&amp;IndexController{},"*:Index")

使用第三個參數,第三個參數就是用來設定對應 method 到函數名,定義如下

*表示任意的 method 都執行該函數

使用 httpmethod:funcname 格式來展示

多個不同的格式使用 ; 分割

多個 method 對應同一個 funcname,method 之間通過 , 來分割

以下是一個 RESTful 的設計示例:

beego.Router("/api/list",&amp;RestController{},"*:ListFood")

    beego.Router("/api/create",&amp;RestController{},"post:CreateFood")

    beego.Router("/api/update",&amp;RestController{},"put:UpdateFood")

    beego.Router("/api/delete",&amp;RestController{},"delete:DeleteFood")

以下是多個 HTTP Method 指向同一個函數的示例:

beego.Router("/api",&amp;RestController{},"get,post:ApiFunc")

以下是不同的 method 對應不同的函數,通過 ; 進行分割的示例:

beego.Router("/simple",&amp;SimpleController{},"get:GetFunc;post:PostFunc")

可用的 HTTP Method:

*:包含以下所有的函數

   get :GET 請求

    post :POST 請求

    put :PUT 請求

    delete :DELETE 請求

    patch :PATCH 請求

    options :OPTIONS 請求

    head :HEAD 請求

如果同時存在 * 和對應的 HTTP Method,那麼優先執行 HTTP Method 的方法,例如同時注冊了如下所示的路由:

beego.Router("/simple",&amp;SimpleController{},"*:AllFunc;post:PostFunc")

那麼執行 POST 請求的時候,執行 PostFunc 而不執行 AllFunc。

        自定義函數的路由預設不支援RESTful的方法,也就是如果你設定了beego.Router("/api",&amp;RestController{},"post:ApiFunc") 這樣的路由,如果請求的方法是POST,那麼不會預設去執行Post函數。

自動比對

使用者首先需要把需要路由的控制器注冊到自動路由中:

beego.AutoRouter(&amp;controllers.ObjectController{})

那麼 beego 就會通過反射擷取該結構體中所有的實作方法,你就可以通過如下的方式通路到對應的方法中:

/object/login 調用 ObjectController 中的 Login 方法 

/object/logout 調用 ObjectController 中的 Logout 方法

除了字首兩個/:controller/:method的比對之外,剩下的 url beego會幫你自動化解析為參數,儲存在 this.Ctx.Input.Params 當中:

/object/blog/2013/09/12 調用 ObjectController 中的 Blog 方法,參數如下:map[0:2013 1:09 2:12]

方法名在内部是儲存了使用者設定的,例如 Login,url 比對的時候都會轉化為小寫,是以,/object/LOGIN 這樣的 url 也一樣可以路由到使用者定義的 Login 方法中。

現在已經可以通過自動識别出來下面類似的所有url,都會把請求分發到 controller 的 simple 方法:

/controller/simple

    /controller/simple.html

    /controller/simple.json

    /controller/simple.xml

可以通過 this.Ctx.Input.Param(“:ext”) 擷取字尾名。 

注解路由

從beego1.3版本開始支援了注解路由,使用者無需在router中注冊路由,隻需要Include相應地controller,然後在controller的method方法上面寫上router注釋(// @router)就可以了,詳細的使用請看下面的例子:

// CMS API

    type CMSController struct {

        beego.Controller

    }

    func (c *CMSController) URLMapping() {

        c.Mapping("StaticBlock", c.StaticBlock)

        c.Mapping("AllBlock", c.AllBlock)

    // @router /staticblock/:key [get]

    func (this *CMSController) StaticBlock() {

    // @router /all/:key [get]

    func (this *CMSController) AllBlock() {

可以在router.go中通過如下方式注冊路由:

beego.Include(&amp;CMSController{})

beego自動會進行源碼分析,注意隻會在dev模式下進行生成,生成的路由放在“/routers/commentsRouter.go”檔案中。

這樣上面的路由就支援了如下的路由:

    GET /staticblock/:key

    GET /all/:key

其實效果和自己通過Router函數注冊是一樣的:

beego.Router("/staticblock/:key", &amp;CMSController{}, "get:StaticBlock")

beego.Router("/all/:key", &amp;CMSController{}, "get:AllBlock")

同時大家注意到新版本裡面增加了URLMapping這個函數,這是新增加的函數,使用者如果沒有進行注冊,那麼就會通過反射來執行對應的函數,如果注冊了就會通過interface來進行執行函數,性能上面會提升很多。 

namespace

//初始化namespace

ns :=

beego.NewNamespace("/v1",

    beego.NSCond(func(ctx *context.Context) bool {

        if ctx.Input.Domain() == "api.beego.me" {

            return true

        }

        return false

    }),

    beego.NSBefore(auth),

    beego.NSGet("/notallowed", func(ctx *context.Context) {

        ctx.Output.Body([]byte("notAllowed"))

    }),

    beego.NSRouter("/version", &amp;AdminController{}, "get:ShowAPIVersion"),

    beego.NSRouter("/changepassword", &amp;UserController{}),

    beego.NSNamespace("/shop",

        beego.NSBefore(sentry),

        beego.NSGet("/:id", func(ctx *context.Context) {

            ctx.Output.Body([]byte("notAllowed"))

        }),

    ),

    beego.NSNamespace("/cms",

        beego.NSInclude(

            &amp;controllers.MainController{},

            &amp;controllers.CMSController{},

            &amp;controllers.BlockController{},

        ),

)

//注冊namespace

beego.AddNamespace(ns)

上面這個代碼支援了如下這樣的請求URL

    GET /v1/notallowed

    GET /v1/version

    GET /v1/changepassword

    POST /v1/changepassword

    GET /v1/shop/123

    GET /v1/cms/ 對應MainController、CMSController、BlockController中得注解路由

而且還支援前置過濾,條件判斷,無限嵌套namespace

namespace的接口如下:

NewNamespace(prefix string, funcs …interface{})

**初始化namespace對象,下面這些函數都是namespace對象的方法,但是強烈推薦使用NS開頭的相應函數注冊,因為這樣更容易通過gofmt工具看的更清楚路由的級别關系**

    NSCond(cond namespaceCond)

支援滿足條件的就執行該namespace,不滿足就不執行

    NSBefore(filiterList …FilterFunc)

    NSAfter(filiterList …FilterFunc)

**上面分别對應beforeRouter和FinishRouter兩個過濾器,可以同時注冊多個過濾器**

 NSInclude(cList …ControllerInterface)

    NSRouter(rootpath string, c ControllerInterface, mappingMethods …string)

    NSGet(rootpath string, f FilterFunc)

    NSPost(rootpath string, f FilterFunc)

    NSDelete(rootpath string, f FilterFunc)

    NSPut(rootpath string, f FilterFunc)

    NSHead(rootpath string, f FilterFunc)

    NSOptions(rootpath string, f FilterFunc)

    NSPatch(rootpath string, f FilterFunc)

    NSAny(rootpath string, f FilterFunc)

    NSHandler(rootpath string, h http.Handler)

    NSAutoRouter(c ControllerInterface)

    NSAutoPrefix(prefix string, c ControllerInterface)

    上面這些都是設定路由的函數,詳細的使用和上面beego的對應函數是一樣的

    NSNamespace(prefix string, params …innnerNamespace)

    **嵌套其他namespace**

    ns :=

    beego.NewNamespace("/v1",

        beego.NSNamespace("/shop",

            beego.NSGet("/:id", func(ctx *context.Context) {

                ctx.Output.Body([]byte("shopinfo"))

            }),

        beego.NSNamespace("/order",

                ctx.Output.Body([]byte("orderinfo"))

        beego.NSNamespace("/crm",

                ctx.Output.Body([]byte("crminfo"))

    )

**下面這些函數都是屬于*Namespace對象的方法:不建議直接使用,當然效果和上面的NS開頭的函數是一樣的,隻是上面的方式更優雅,寫出來的代碼更容易看**  

    Cond(cond namespaceCond)

    支援滿足條件的就執行該namespace,不滿足就不執行,例如你可以根據域名來控制namespace

    Filter(action string, filter FilterFunc)

    action表示你需要執行的位置,before和after分别表示執行邏輯之前和執行邏輯之後的filter

    Router(rootpath string, c ControllerInterface, mappingMethods …string)

    AutoRouter(c ControllerInterface)

    AutoPrefix(prefix string, c ControllerInterface)

    Get(rootpath string, f FilterFunc)

    Post(rootpath string, f FilterFunc)

    Delete(rootpath string, f FilterFunc)

    Put(rootpath string, f FilterFunc)

    Head(rootpath string, f FilterFunc)

    Options(rootpath string, f FilterFunc)

    Patch(rootpath string, f FilterFunc)

    Any(rootpath string, f FilterFunc)

    Handler(rootpath string, h http.Handler)

    Namespace(ns …*Namespace)多的例子代碼```

//APIS

    beego.NewNamespace("/api",

        //此處正式版時改為驗證加密請求

        beego.NSCond(func(ctx *context.Context) bool {

            if ua := ctx.Input.Request.UserAgent(); ua != "" {

                return true

            }

            return false

        beego.NSNamespace("/ios",

            //CRUD Create(建立)、Read(讀取)、Update(更新)和Delete(删除)

            beego.NSNamespace("/create",

                // /api/ios/create/node/

                beego.NSRouter("/node", &amp;apis.CreateNodeHandler{}),

                // /api/ios/create/topic/

                beego.NSRouter("/topic", &amp;apis.CreateTopicHandler{}),

            ),

            beego.NSNamespace("/read",

                beego.NSRouter("/node", &amp;apis.ReadNodeHandler{}),

                beego.NSRouter("/topic", &amp;apis.ReadTopicHandler{}),

            beego.NSNamespace("/update",

                beego.NSRouter("/node", &amp;apis.UpdateNodeHandler{}),

                beego.NSRouter("/topic", &amp;apis.UpdateTopicHandler{}),

            beego.NSNamespace("/delete",

                beego.NSRouter("/node", &amp;apis.DeleteNodeHandler{}),

                beego.NSRouter("/topic", &amp;apis.DeleteTopicHandler{}),

            )

示例代碼:

package routers

import (

    "fmt"

    "quickstart/controllers"

     "github.com/astaxie/beego"

         "github.com/astaxie/beego/context"

func init() {

    //預設路由

    beego.Router("/", &amp;controllers.MainController{})

    //基本get路由

    beego.Get("/get", func(ctx *context.Context) {

        ctx.Output.Body([]byte("this is get"))

    })

    //基本post路由

    beego.Post("/post", func(ctx *context.Context) {

        ctx.Output.Body([]byte("this is post"))

    //響應任何請求的路由

    beego.Any("/any", func(ctx *context.Context) {

        ctx.Output.Body([]byte("this is any"))

    //加載命名空間的路由(推薦)

    newPath()

}

func newPath() {

        beego.NewNamespace("new",

            //  beego.NSCond(func(ctx *context.Context) bool {

            //      if ctx.Input.Domain() == "api.beego.me" {

            //          return true

            //      }

            //      return false

            //  }),

            beego.NSBefore(func(ctx *context.Context) {

                fmt.Println("這是前置過濾函數")

            beego.NSGet("/newget", func(ctx *context.Context) {

                ctx.Output.Body([]byte("this is new get"))

        )

    beego.AddNamespace(ns)