beego
1 2
| export GOPATH="$HOME/go" export PATH="$GOPATH/bin:$PATH"
|
1 2 3 4
| 创建项目 bee new hello 运行项目 bee run
|
控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package controllers
import ( beego "github.com/beego/beego/v2/server/web" )
type MainController struct { beego.Controller }
func (c *MainController) Get() { c.Data["data"] = "hello myself" c.TplName = "test.html" }
|
渲染
1 2 3 4 5 6 7 8 9 10
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册界面</title> </head> <body> {{.data}} </body> </html>
|
构造控制器
1 2 3
| type GetController struct { beego.Controller }
|
1 2 3 4
| func (b *GetController) Get() { b.Data["data"] = "hello get" b.TplName = "test.html" }
|
router.go
1
| beego.Router("/get", &controllers.GetController{})
|
先router.go路由进行匹配,路由器在到控制器,然后控制器对视图进行渲染
beego 内嵌ORM框架 操作数据库
创建表
main.go 引入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package models
import ( "github.com/beego/beego/v2/client/orm" _ "github.com/go-sql-driver/mysql" )
type User struct { Id int Name string Passwd string }
func init(){ orm.RegisterDataBase("default", "mysql", "root:luo19961001@tcp(127.0.0.1:8889)/class?charset=utf8") orm.RegisterModel(new(User)) orm.RunSyncdb("default", false, true) }
|
插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package controllers
import ( "github.com/beego/beego/v2/client/orm" beego "github.com/beego/beego/v2/server/web" "hello/models" )
type MainController struct { beego.Controller } type GetController struct { beego.Controller }
func (c *MainController) Get() { o := orm.NewOrm() user := models.User{} user.Id = 2 user.Name = "admin" user.Passwd = "admin123" o.Insert(&user) c.Data["data"] = "hello xxx" c.TplName = "test.html" } func (c *MainController) Post() { c.Data["data"] = "hello xxx" c.TplName = "test.html" }
func (b *GetController) Get() { b.Data["data"] = "hello get" b.TplName = "test.html" }
|