4.注解路由
最后更新于:2022-04-02 04:53:20
注解路由
注意:
beego 自动会进行源码分析,注意只会在 dev 模式下进行生成,生成的路由放在 “/routers/commentsRouter.go” 文件中。
将配置文件中的 runmode 更改为 dev 模式 。
或者 在 main函数添加:beego.BConfig.RunMode ="dev"
~~~
|-- routers
| `-- router.go
~~~
代码:
~~~
package routers
import (
admin "project/admin/controllers"
"github.com/astaxie/beego"
)
func init() {
// 注解路由
beego.Include(&admin.UserController{})
}
~~~
~~~
|-- admin
| |--controllers
| `-- user.go
~~~
代码:
~~~
package admin
import (
"fmt"
"github.com/astaxie/beego"
)
type UserController struct {
beego.Controller
}
func (c *UserController) URLMapping() {
c.Mapping("Index", c.Index)
c.Mapping("Test", c.Test)
}
// @router /admin/index/
func (this *UserController) Index() {
this.Ctx.WriteString("这是注释路由 user/index")
}
// @router /admin/test/user_name/:user_name/user_id/:user_id [get]
func (this *UserController) Test() {
user_name := this.Ctx.Input.Param(":user_name")
values := this.Ctx.Input.Params()
str := fmt.Sprintln(values)
this.Ctx.WriteString("这是注释路由 user/test , values is " + str + " user name is " + user_name)
}
~~~
路由目录下自动生成 :commentsRouter_admin_controllers.go
~~~
|-- routers
| `-- router.go
| `-- commentsRouter_admin_controllers.go
~~~
commentsRouter_admin_controllers.go 自动生成的代码:
~~~
package routers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context/param"
)
func init() {
beego.GlobalControllerRouter["project/admin/controllers:UserController"] = append(beego.GlobalControllerRouter["project/admin/controllers:UserController"],
beego.ControllerComments{
Method: "Index",
Router: `/admin/index/`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["project/admin/controllers:UserController"] = append(beego.GlobalControllerRouter["project/admin/controllers:UserController"],
beego.ControllerComments{
Method: "Test",
Router: `/admin/test/user_name/:user_name/user_id/:user_id`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Params: nil})
}
~~~
浏览器访问:
http://127.0.0.1:8080/admin/index
浏览器输出:
这是注释路由 user/index
浏览器访问:
http://127.0.0.1:8080/admin/test/user_name/user1/user_id/123
浏览器输出:
这是注释路由 user/test , values is map[:user_name:user1 :user_id:123]
user name is user1
';