5.namespace
最后更新于:2022-04-02 04:53:23
namespace
~~~
|-- routers
| `-- router.go
~~~
代码:
~~~
package routers
import (
admin "project/admin/controllers"
"github.com/astaxie/beego"
)
func init() {
//初始化 namespace
ns :=
beego.NewNamespace("/admin",
beego.NSRouter("/user/add/:user_name:/:user_pwd:/:mobile", &admin.UserController{}, "*:Insert"),
beego.NSNamespace("/user",
beego.NSInclude(
&admin.UserController{},
),
),
)
//注册 namespace
beego.AddNamespace(ns)
}
~~~
~~~
|-- 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 /index/
func (this *UserController) Index() {
this.Ctx.WriteString("这是注释路由 user/index")
}
// @router /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)
}
func (this *UserController) Insert() {
user_name := this.Ctx.Input.Param(":user_name")
values := this.Ctx.Input.Params()
str := fmt.Sprintln(values)
this.Ctx.WriteString("这是namespace user/add , values is " + str + " user name is " + user_name)
}
~~~
浏览器访问:
http://127.0.0.1:8080/admin/user/index
浏览器输出:
这是注释路由 user/index
浏览器访问:
http://127.0.0.1:8080/admin/user/test/user_name/user1/user_id/123
浏览器输出:
这是注释路由 user/test , values is map[:user_name:user1 :user_id:123]
user name is user1
浏览器输出:
http://127.0.0.1:8080/admin/user/add/user1/md5pwd/15688889999
浏览器输出:
这是namespace user/add , values is map[:user_name:user1 :user_pwd:md5pwd :mobile:15688889999]
user name is user1
';