Beego-ROUTER Beego-ROUTER
阿新 • • 發佈:2019-02-06
對GOPATH的配置
其實GOPATH可以使用多個路徑 用來區別GOPATH的外掛和開發 eg:/Users/Z/develop/gopath:/Users/Z/Dropbox/gopath
Beego的幾個重要功能
new Creates a Beego application
run Run the application by starting a local development server
pack Compresses a Beego application into a single file
api Creates a Beego API application
beego路由型別
函式級別的註冊 RESTFul (PAST,GET 。。。。)
controller級別的註冊自動化對映
更加自動化的handler註冊,即實現ServerHTTP(respost,request)函式都可以
基礎路由
beego.Get(router,beego.FilterFunc)
beego.post(router,beego.FilterFunc)
beego.Put(router,beego.FilterFunc)
beego.Head(router,beego.FilterFunc)
beego.Option(router,beego.FilterFunc)
beego.Delete(router,beego.FilterFunc )
beego.Any(router,beego.FilterFunc)
// 基礎Get請求 beego.Get("/", func(ctx *context.Context){ ctx.Output.Body([]byte("hello world")) }) // 基礎post請求 beego.Post("/foo", fun(ctx *context.Context){ ctx.OutPut.Body([]byte("bar")) }) // 任意HTTP請求 beego.Any("/falice", fun(ctx *context.Context){ ctx.OutPut .Body([]byte("bar")) })
基礎路由之controller
beego.Router(router,controller)
type ObjectController struct { beego.Controller } func (this *ObjectController) Get() { obs := models.GetAll() this.Data["json"] = obs this.ServerJson() } beego.Router("/object", &ObjectController{})
對映路由
// 一個RESTful的設計示例 beego.Router("/api/list",&ResrController{},"*:ListFood") beego.Router("/api/create",&ResrController{},"post:CreatFood") beego.Router("/api/updata",&ResrController{},"put:UpdateFood") beego.Router("/api/delete",&ResrController{},"delete:DeleteFood") // 多個HTTP Method beego.Router("/api",&RestController{},"get,post:ApiFunc") // 不同Method對應不同的函式 beego.Router("/simple",&SimpleController{})
自動化路由
beego.AutoRouter(&controllers.ObjectController{}) // 請求如下 /object/login // 呼叫ObjectController 中的 Login /object/logout // 呼叫ObjectController 中的 Logout
自動化路由之API模式解析
/controller/simple /controller/simple.html /controller/simple.json /controller/simple.rss 可以通過 this.Ctx.Input.Param(":ext")獲取字尾
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)
ns:=NewNameSpace("V1")
ns.Cond(func(ctx *context.Context)bool{
if ctx.Input.Domain() == "api.beego.mo" {
return true
}
return false
})
Filter(action string,)