beego作为现在最流行的golang版本的web开发框架,以其架构的方便易懂和功能的强大很快得到了大家的认可。本文主要就如何使用beego连接mysql和beego的namespace特性进行讲解:
首先,beego最方便之处就是可以直接通过bee工具生成代码框架,这样极大的降低了beego的使用难度。
下面以连接本地部署的mysql为例,只要运行如下命令,就可以生成一套beego的框架:
bee api appname -conn="root:root@tcp(127.0.0.1:3306)/dbname"
root:root是mysql的连接的用户名和密码,这个需要在mysql中配置好,并赋予远程连接能力。@tcp(127.0.0.1:3306)是指通过tcp方式连接mysql,mysql默认开启的是3306端口。dbname是你在mysql中创建的数据库名称。
生成好之后默认会有如下文件结构:
boyaweb/
├── conf
│ └── app.conf //存放beego的配置文件
├── controllers //用来实现对应router消息接收后,处理GET,UPDATE,POST以及DELETE请求的
├── main.go //beego的main函数,自动生成
├── models //存放需要解析的模块,可以是数据库中的表结构
├── routers
│ └── router.go //实现不同url的路由和跳转
└── tests
对于namespace的方式归类router可以方便对大量url进行归类处理,方便运维。如下
router.go中,最后可供访问的便是 127.0.0.1:8080/v1/student/xxxx, xxxx为id的具体值,在NSRouter函数,可以看到最后需要controller参数,这个controller就是实现具体收到消息的处理:
package routersimport ( "github.com/astaxie/beego" "boyaweb/controllers")func init() { ns := beego.NewNamespace("/v1", beego.NSNamespace("/student", beego.NSRouter("/:id", &controllers.StudentController{})), ) beego.AddNamespace(ns)}
controller中实现了GET请求的处理,params := this.Ctx.Input.Params() 获取url中的参数,本例为:id;this.Ctx.WriteString(info) 将info写入响应消息:
package controllersimport ( "boyaweb/models" "fmt" "github.com/astaxie/beego")type StudentController struct { beego.Controller}func (this * StudentController)URLMapping(){ this.Mapping("GET", this.Get)}func (this *StudentController) Get() { params := this.Ctx.Input.Params() for key, value := range params { info := fmt.Sprintf("%s: %s\n", key, value) this.Ctx.WriteString(info) } students := models.QuerUser() for _,s := range students{ info := fmt.Sprintf("id: %d, name: %s, score: %d\n", s.Id_RENAME, s.Name, s.Score) this.Ctx.WriteString(info) } return}
module.go 定义好数据库中的表结构,并将查询好的结构返回:
package modelsimport ( "fmt" "github.com/astaxie/beego/orm")type Student struct {cichu Id_RENAME int `orm:"column(id);pk"` // 此处需要增加主键标志pk,否则会报错,参考https://blog.csdn.net/Charles_Thanks/article/details/80502829 Name string `orm:"column(name);size(255)"` Score int `orm:"column(score)"`}func init() { // 需要在init中注册定义的model orm.RegisterModel(new(Student)) orm.Debug = true // 是否开启调试模式 调试模式下会打印出sql语句}func QuerUser() []Student { var userData []Student qb, _ := orm.NewQueryBuilder("mysql") // 构建查询对象 qb.Select("*").From("student"). OrderBy("score").Desc(). Limit(3).Offset(0) // 导出 SQL 语句 sql := qb.String() // 执行 SQL 语句 o := orm.NewOrm() i,err := o.Raw(sql).QueryRows(&userData) fmt.Print(i,err) fmt.Println(userData) return userData}
完成如上修改之后,便可以运行main.go了,效果如下:
文章来源:智云一二三科技
文章标题:Beego 的namespace和连接mysql的方法
文章地址:https://www.zhihuclub.com/7129.shtml