This is a creation in Article, where the information may have evolved or changed.
How to use Beego to develop service-side applications?
: LIJIAOCN created: 2017/10/23 14:01:13
- Description
- Quick Start
- Installation
- Create an App
- Compile run
- Package release
- Code generation
- Development documentation
- Directory Structure Description
- Using configuration Files
- Beego Default Parameters
- Routing settings
- How routes are expressed
- Set up routing directly
- Set up a route in the form of a registered handler
- Auto-enrollment Routing
- Registering Routes with annotations
- Managing Routes with Namespace
- Nsafter () requiring special attention
- Working with databases
- Database Migration (migration)
- Beego. Controller handles HTTP requests
- Reference
Description
Beego is a domestic team open source Golang development framework, is a focus on and use of the high price of the project.
Quick Start
A very simple example is given in the Beego QuickStart.
Installation
First you need to install the Beego and Bee tools:
$ go get -u github.com/astaxie/beego$ go get -u github.com/beego/bee
In order to be able to use the bee
command directly, it needs to be $GOPATH/bin
added to the $PATH
variable.
Create an App
To create an app called Hello, you can choose a web app, or an API app:
$ bee new hello //创建一个web应用$ bee api hello //创建一个api应用
After execution finishes, a directory named under the current directory is created hello
:
.|____hello| |____conf| | |____app.conf| |____controllers| | |____default.go| |____main.go| |____models| |____routers| | |____router.go| |____static| | |____css| | |____img| | |____js| | | |____reload.min.js| |____tests| | |____default_test.go| |____views| | |____index.tpl
Compile run
Enter the Hello directory, execute bee run
, compile, run:
$ cd hello/$ bee run______| ___ \| |_/ / ___ ___| ___ \ / _ \ / _ \| |_/ /| __/| __/\____/ \___| \___| v1.9.12017/10/23 14:33:05 INFO 0001 Using 'hello' as 'appname'2017/10/23 14:33:05 INFO 0002 Initializing watcher...2017/10/23 14:33:06 SUCCESS 0003 Built Successfully!2017/10/23 14:33:06 INFO 0004 Restarting 'hello'...2017/10/23 14:33:06 SUCCESS 0005 './hello' is running...2017/10/23 14:33:06 [I] [asm_amd64.s:2197] http server Running on http://:8080
Package release
Project Package Release:
$ bee pack
Code generation
Generate Models:
bee generate model user -fields="name:string,age:int"
Generate Controller:
bee generate controller user
Generate View:
bee generate view user
To generate a document:
bee generate docs
Development documentation
The Beego is described in detail in the Beego development documentation.
Directory Structure Description
.|____hello| |____conf <- 配置文件| | |____app.conf| |____controllers <- 控制器,即http请求的handler| | |____default.go| |____main.go <- main函数| |____models| |____routers <- 路由,将url关联到controllers| | |____router.go| |____static <- 静态文件| | |____css| | |____img| | |____js| | | |____reload.min.js| |____tests <- 测试| | |____default_test.go| |____views <- 页面模版,controller中可以直接渲染对应的tpl文件| | |____index.tpl
Using configuration Files
The Beego parameter configuration explains how to use the configuration file and how to configure the parameters.
Beego default parsing of files under the application directory conf/app.conf
, configuration items can be beego.AppConfig.*
read by:
beego.AppConfig.String("mysqluser")
Beego. AppConfig contains several methods:
Set(key, val string) errorString(key string) stringStrings(key string) []stringInt(key string) (int, error)Int64(key string) (int64, error)Bool(key string) (bool, error)Float(key string) (float64, error)DefaultString(key string, defaultVal string) stringDefaultStrings(key string, defaultVal []string)DefaultInt(key string, defaultVal int) intDefaultInt64(key string, defaultVal int64) int64DefaultBool(key string, defaultVal bool) boolDefaultFloat(key string, defaultVal float64) float64DIY(key string) (interface{}, error)GetSection(section string) (map[string]string, error)SaveConfigFile(filename string) error
The section can be configured in the configuration file, specifying the section to be used by RunMode, for example:
appname = beepkghttpaddr = "127.0.0.1"httpport = 9090runmode ="dev"autorender = falserecoverpanic = falseviewspath = "myview"[dev]httpport = 8080[prod]httpport = 8088[test]httpport = 8888
For section configuration items, read in the following way 模式::配置参数名
:
beego.AppConfig.String(“dev::mysqluser”)
Environment variables can be used in the configuration file:
runmode = "${ProRunMode||dev}"httpport = "${ProPort||9090}"
Load a specific configuration file, you can load multiple profiles, key cannot conflict:
beego.LoadAppConfig("ini", "conf/app2.conf")beego.LoadAppConfig("ini", "conf/app3.conf")
Beego Default Parameters
The default parameters of the Beego are all saved in beego.BConfig
. , you can access and modify all of the configuration information.
A key with the same name (case-insensitive) set in the configuration file overrides the default value, for example:
appname = hellohttpport = 8080runmode = dev[dev]AutoRender=false #会覆盖beego.BConfig.WebConfig.AutoRender的默认值[test][prod]
App Configuration:
beego.BConfig.AppName = "beego"beego.BConfig.RunMode = "dev"beego.BConfig.RouterCaseSensitive = truebeego.BConfig.ServerName = "beego"beego.BConfig.RecoverPanic = truebeego.BConfig.EnableGzip = falsebeego.BConfig.MaxMemory = 1 << 26beego.BConfig.EnableErrorsShow = truebeego.BConfig.EnableErrorsRender = true
Web configuration:
beego.BConfig.WebConfig.AutoRender = truebeego.BConfig.WebConfig.EnableDocs = truebeego.BConfig.WebConfig.FlashName = "BEEGO_FLASH"beego.BConfig.WebConfig.FlashSeperator = "BEEGOFLASH"beego.BConfig.WebConfig.DirectoryIndex = falsebeego.BConfig.StaticDir = staticbeego.BConfig.WebConfig.StaticExtensionsToGzip = []string{".css", ".js"}beego.BConfig.WebConfig.TemplateLeft="beego.BConfig.WebConfig.TemplateRight="beego.BConfig.WebConfig.ViewsPath="views"beego.BConfig.WebConfig.EnableXSRF = falsebeego.BConfig.WebConfig.XSRFKEY = "beegoxsrf"beego.BConfig.WebConfig.XSRFExpire = 0
Monitoring configuration:
beego.BConfig.Listen.Graceful=falsebeego.BConfig.Listen.ServerTimeOut=0beego.BConfig.Listen.ListenTCP4 = "tcp4"beego.BConfig.Listen.EnableHTTP = truebeego.BConfig.Listen.HTTPAddr = ""beego.BConfig.Listen.HTTPPort = 8080beego.BConfig.Listen.EnableHTTPS = falsebeego.BConfig.Listen.HTTPSAddr = ""beego.BConfig.Listen.HTTPSPort = 10443beego.BConfig.Listen.HTTPSCertFile = "conf/ssl.crt"beego.BConfig.Listen.HTTPSKeyFile = "conf/ssl.key"beego.BConfig.Listen.EnableAdmin = falsebeego.BConfig.Listen.AdminAddr = "localhost"beego.BConfig.Listen.AdminPort = 8088beego.BConfig.Listen.EnableFcgi = falsebeego.BConfig.Listen.EnableStdIo = false
Session configuration:
beego.BConfig.WebConfig.Session.SessionOn = falsebeego.BConfig.WebConfig.Session.SessionProvider = ""beego.BConfig.WebConfig.Session.SessionName = "beegosessionID"beego.BConfig.WebConfig.Session.SessionGCMaxLifetime = 3600beego.BConfig.WebConfig.SessionProviderConfigbeego.BConfig.WebConfig.Session.SessionCookieLifeTime = 3600beego.BConfig.WebConfig.Session.SessionAutoSetCookie = truebeego.BConfig.WebConfig.Session.SessionDomain = ""
Log configuration:
beego.BConfig.Log.AccessLogs = falsebeego.BConfig.Log.FileLineNum = truebeego.BConfig.Log.Outputs = map[string]string{"console": ""}
Routing settings
The Beego supports three routes: underlying routing, regular routing, and automatic routing.
How routes are expressed
Supports writing routes in a regular manner, referencing sinatra
the routing implementation.
路由规则 可以匹配/api/?:id ----> /api/, /api/123 id=123/api/:id ----> /api/123 id=123/api/:id([0-9]+) ----> /api/123 id=123/user/:username([\w]+) ----> /user/abc username=abc/download/*.* ----> /download/file/api.xml path=file/api ext=xml/download/ceshi/* ----> /download/cechis/file/api.json splat=file/api.json/:id:int ----> 等同于/:id([0-9]+)/:hi:string ----> 等同于/:hi([\w]+)/cms_:id([0-9]+).html ----> /cms_123.html id=123
*context.Context
the variables in the route can be read by the Input.param () method:
ctx.Input.Param(":id")
In the controller, the variables in the route are obtained in the following way, this is the 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")
Set up routing directly
In the routers/router.go
settings, you can set the route directly using the following underlying function:
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)
For example:
//响应post /alicebeego.Post("/alice",func(ctx *context.Context){ ctx.Output.Body([]byte("bob"))})//响应到/foo的所有http请求beego.Any("/foo",func(ctx *context.Context){ ctx.Output.Body([]byte("bar"))})
Set up a route in the form of a registered handler
You can also use beego.Handler(router, http.Handler)
the handler to set the route:
beego.Handler("/rpc", s)
Beego. Handler default is 完全匹配
that it is not a prefix match. You can customize the mapping of HTTP request methods and processing functions:
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")
The format of a custom mapping relationship is "request method: Function name", the request method has the following:
*: 包含以下所有的函数,优先级低于下面的方法get: GET 请求post: POST 请求put: PUT 请求delete: DELETE 请求patch: PATCH 请求options: OPTIONS 请求head: HEAD 请求
Auto-enrollment Routing
In addition beego.AutoRouter($controllers.ObjectController{})
, routes are automatically generated by reflection as a method in object.
Registering Routes with annotations
Add the router comment to the controller's method, and the beego.Include(&Controller)
route is automatically registered when the controller is introduced in the Router.go.
For example:
// 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() {}
Then in the Router.go:
beego.Include(&CMSController{})
Beego will automatically conduct source analysis, if yes dev模式
, will be in the Routers/commentxxx.go file.
Managing Routes with Namespace
The namespace supports pre-set, and can be used to pre-filter the routing, conditional judgment.
The namespace interface is as follows:
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)
Example:
//初始化 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)
The following routes are registered:
GET /v1/notallowedGET /v1/versionGET /v1/changepasswordPOST /v1/changepasswordGET /v1/shop/123GET /v1/cms/ 对应 MainController、CMSController、BlockController 中得注解路由
Nsafter () requiring special attention
The filter function registered by Nsafter () will be called at the end of the request processing, but be aware of the bee 1.9.0:
beego.NSAfter does not work after controller.ServeJSON
Related issue:
Note Routing cannot be entered into Nsbeforecontroller.servejson should work would with Beego. Nsafter
You can experiment with the code in the Github:study-beego.
Working with databases
Beego implements Beego Orm in the Digango ORM and SQLAlchemy, currently supports three drivers:
MySQL:github.com/go-sql-driver/mysqlPostgreSQL:github.com/lib/pqSqlite3:github.com/mattn/go-sqlite3
In the model file generated by Beego, the model is automatically registered to the ORM, for example:
bee generate model user -fields="name:string,age:int"
The generated code models/user.go
is registered in init ():
func init() {orm.RegisterModel(new(User))}
Therefore, you only need to manually write the ORM initialization code, for example in Main.go:
func init() {orm.RegisterDataBase("default", "mysql", "root:@tcp(127.0.0.1:3306)/mysql?charset=utf8", 30)}
Database Migration (migration)
The database Migration feature allows the database to be upgraded and rolled back.
Build the migration file, which user
is the table name, which fields
is the table structure:
bee generate migration user -driver=mysql -fields="name:string,age:int"
After running, the file is generated:
|____database| |____migrations| | |____20171024_154037_user.go
After you have created the database named in the database study-beego
, execute the following command:
bee migrate -driver=mysql -conn="root:@tcp(127.0.0.1:3306)/study-beego"
The tables in the Study-beego are created or updated, and the updates are recorded in the migrations
table named.
Migrate subcommand refresh
, rollback
execution failed for unknown reason.
Beego. Controller handles HTTP requests
Note that in 1.9.0, you need to set up in the configuration to have copyrequestbody=true
data in 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()}
Reference
- Beego Home
- Beego Quick Start
- Beego Development Documentation
- Beego parameter Configuration
- Note Route cannot enter Nsbefore
- Controller. Servejson should work would with Beego. Nsafter
- Github:study-beego