beego框架學習(二) -路由設置


路由設置

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

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

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

         ctx.Output.Body([]byte("hello world"))

    })

  

基本 POST 路由

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

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

    })

  

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

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

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

    })

  

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

 beego.Get(router, beego.FilterFunc)

    beego.Post(router, beego.FilterFunc)

    beego.Put(router, beego.FilterFunc)

    beego.Head(router, beego.FilterFunc)

    beego.Options(router, beego.FilterFunc)

    beego.Delete(router, beego.FilterFunc)

    beego.Any(router, beego.FilterFunc)

  

支持自定義的handler實現

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

s := rpc.NewServer()

    s.RegisterCodec(json.NewCodec(), "application/json")

    s.RegisterService(new(HelloService), "")

    beego.Handler("/rpc", s)

  

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 的請求方式。 
固定路由

固定路由也就是全匹配的路由,如下所示:

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

    beego.Router("/admin", &admin.UserController{})

    beego.Router("/admin/index", &admin.ArticleController{})

    beego.Router("/admin/addpkg", &admin.AddController{})

  

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

為了用戶更加方便的路由設置,beego 參考了 sinatra 的路由實現,支持多種方式的路由:

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

 

    默認匹配 //匹配 /api/123 :id = 123 可以匹配/api/這個URL

 

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

 

    默認匹配 //匹配 /api/123 :id = 123 不可以匹配/api/這個URL

 

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

 

    自定義正則匹配 //匹配 /api/123 :id = 123

 

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

 

    正則字符串匹配 //匹配 /user/astaxie :username = astaxie

 

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

 

    *匹配方式 //匹配 /download/file/api.xml :path= file/api :ext=xml

 

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

 

    *全匹配方式 //匹配 /download/ceshi/file/api.json :splat=file/api.json

 

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

 

    int 類型設置方式,匹配 :id為int類型,框架幫你實現了正則([0-9]+)

 

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

 

    string 類型設置方式,匹配 :hi為string類型。框架幫你實現了正則([\w]+)

 

    beego.Router(“/cms_:id([0-9]+).html”, &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("/",&IndexController{},"*:Index")

  • 1

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

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

使用 httpmethod:funcname 格式來展示

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

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

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

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

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

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

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

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

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

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

beego.Router("/simple",&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",&SimpleController{},"*:AllFunc;post:PostFunc")

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

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

自動匹配

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

beego.AutoRouter(&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(&CMSController{})

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

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

    GET /staticblock/:key

    GET /all/:key

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

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

beego.Router("/all/:key", &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", &AdminController{}, "get:ShowAPIVersion"),

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

    beego.NSNamespace("/shop",

        beego.NSBefore(sentry),

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

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

        }),

    ),

    beego.NSNamespace("/cms",

        beego.NSInclude(

            &controllers.MainController{},

            &controllers.CMSController{},

            &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",

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

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

            }),

        ),

        beego.NSNamespace("/crm",

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

                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)

 

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

 

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

//APIS

ns :=

    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", &apis.CreateNodeHandler{}),

                // /api/ios/create/topic/

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

            ),

            beego.NSNamespace("/read",

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

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

            ),

            beego.NSNamespace("/update",

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

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

            ),

            beego.NSNamespace("/delete",

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

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

            )

        ),

    )

 

beego.AddNamespace(ns)

示例代碼:

package routers

 

import (

    "fmt"

    "quickstart/controllers"

     "github.com/astaxie/beego"

         "github.com/astaxie/beego/context"

)

func init() {

    //默認路由

    beego.Router("/", &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() {

    ns :=

        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)

}

 


免責聲明!

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



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