一、创建项目
使用bee工具创建一个项目test
bee new test
结果:
二、数据库创建
navicat打开数据库新建一个,数据库名test,表明example,字段如下:
添加两条数据:
三、代码
代码使用goland打开
1、models下新建test.go文件
代码如下:
package models
import (
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
type Example struct {
Id int
Name string
Message string
Age int
}
func init() {
// root 用户名,123456 密码,127.0.0.1 数据库ip,3306 数据库端口
orm.RegisterDataBase("default","mysql","root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
orm.RegisterModel(new(Example))
}
这个时候 _ “github.com/go-sql-driver/mysql” 这行代码会标红,原因是没有安装ORM,那我们就安装一下ORM,cmd进入项目根目录,执行代码如下:
go get github.com/astaxie/beego/orm
执行完后,关闭goland重新打开代码即可,
2、controllers下新建test.go文件
代码如下:
package controllers
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
type TestController struct {
beego.Controller
}
type JSONS struct {
Code int
Msg string
Data []orm.Params
}
func (c *TestController) Get() {
o := orm.NewOrm()
var example1 []orm.Params
example, err := o.QueryTable("example").Filter("name","张三").Values(&example1,"id","message","age")
if err == nil {
fmt.Printf("Result Nums: %d\n", example)
data := &JSONS{200,"请求成功",example1}
c.Data["json"] = data
c.ServeJSON()
}
}
3、routers文件加下router.go文件中添加路由,
代码如下:
package routers
import (
"github.com/astaxie/beego"
"test/controllers"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test",&controllers.TestController{})
}
4、main.go添加执行models的初始化方法
代码如下:
package main
import (
_ "test/routers"
_ "test/models"
"github.com/astaxie/beego"
)
func main() {
beego.Run()
}
四、运行
cmd进入项目test根目录,bee run运行项目
访问127.0.0.1:8080/test,成功!结果如下:
版权声明:本文为weixin_43118090原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。