用beego开发服务端应用
*: 包含以下所有的函数,优先级低于下面的方法get: GET 请求post: POST 请求put: PUT 请求delete: DELETE 请求patch: PATCH 请求options: OPTIONS 请求head: HEAD 请求
自动注册路由
另外还有beego.AutoRouter($controllers.ObjectController{}),会自动通过反射为Object中的方法生成路由。
通过注解注册路由
在controller的方法上面加上router注释,router.go中通过beego.Include(&Controller)引入controller的时候会自动注册路由。
例如:
// CMS APItype 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/commentXXX.go文件。
使用namespace管理路由
namespace支持前套,并且可以对包含其中对路由进行前置过滤、条件判断。
namespace接口如下:
NewNamespace(prefix string, funcs …interface{}) 初始化 namespace 对象NSCond(cond namespaceCond) 支持满足条件才namespaceNSBefore(filiterList …FilterFunc)NSAfter(filiterList …FilterFunc)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)
示例:
//初始化 namespacens :=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{},),),)//注册 namespacebeego.AddNamespace(ns)
注册了以下的路由:
GET /v1/notallowedGET /v1/versionGET /v1/changepasswordPOST /v1/changepasswordGET /v1/shop/123GET /v1/cms/ 对应 MainController、CMSController、BlockController 中得注解路由
需要特别注意的NSAfter()
NSAfter()注册的filter函数会在请求处理结束的时候被调用,但是要注意在bee 1.9.0中:
beego.NSAfter does not work after controller.ServeJSON相关的issue:
注解路由无法进入NSBefore controller.ServeJSON should work will with beego.NSAfter
可以用github: study-beego里的的代码试验一下。
使用数据库
beego仿照Digango ORM和SQLAlchemy实现beego ORM,当前支持三个驱动:
MySQL:github.com/go-sql-driver/mysqlPostgreSQL:github.com/lib/pqSqlite3:github.com/mattn/go-sqlite3
beego生成的model文件中,会自动将model注册到orm,例如:
bee generate model user -fields='name:string,age:int'生成的代码models/user.go中会在init()中注册:
func init() {orm.RegisterModel(new(User))}
因此只需要手工书写orm初始化的代码,譬如在main.go中:
func init() {orm.RegisterDataBase('default', 'mysql', 'root:@tcp(127.0.0.1:3306)/mysql?charset=utf8', 30)}
数据库迁移(migration)
数据库迁移功能可以数据库进行升级、回滚操作。
生成迁移文件,user是表名,fields是表结构:
bee generate migration user -driver=mysql -fields='name:string,age:int'
运行后,生成了文件:
|____database| |____migrations| | |____20171024_154037_user.go
在数据库中创建了名为study-beego的数据库后,执行下面的命令:
bee migrate -driver=mysql -conn='root:@tcp(127.0.0.1:3306)/study-beego'
study-beego中的表将会被创建或者更新,并在名为migrations的表中记录更新。
migrate的子命令
refresh、rollback执行失败,原因不明。beego.Controller处理http请求
注意,在1.9.0中,需要在配置中设置
copyrequestbody=true以后,c.Ctx.Input.RequestBody中才有数据。
func (c *UserController) Post() {var v models.Userjson.Unmarshal(c.Ctx.Input.RequestBody, &v)fmt.Println(v)if _, err := models.AddUser(&v); err == nil {c.Ctx.Output.SetStatus(201)c.Data['json'] = v} else {c.Data['json'] = err.Error()}c.ServeJSON()}

