http://beego.me/docs/mvc/model/object.md
入口文件main.go
package main
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/MysqL"
"testslim/models"
_ "testslim/routers"
)
func init() {
orm.RegisterDriver("MysqL",orm.DR_MysqL)
orm.RegisterDataBase("default","MysqL","test:pwd@tcp(ip:3306)/tablename?charset=utf8")
orm.RegisterModelWithPrefix("he_",new(models.Students))
}
func main() {
beego.Run()
}
models目录下存放model文件
models.go:
package models
type Students struct {
Id int
Nickname string
CreateTime int
}
controllers目录下存放控制器
package controllers
import (
//"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/MysqL"
"testslim/models"
//"time"
)
func (t *TestController) Testmodel() {
o := orm.NewOrm()
o.Using("default")
//ins
// student := new(models.Students)
// student.Nickname = "Test From Go"
// student.CreateTime = int(time.Now().Unix())
//fmt.Println(o.Insert(student))
//read
// student := models.Students{Id: 10001}
// err := o.Read(&student)
// if err == orm.ErrNoRows {
// t.Data["json"] = "No rows"
// } else if err == orm.ErrMissPK {
// t.Data["json"] = "No pk"
// } else {
// t.Data["json"] = student
// }
var stds []*models.Students
o.QueryTable("he_students").Limit(10).All(&stds)
t.Data["json"] = map[string][]*models.Students{"stds": stds}
t.ServeJson()
}
最后在路由routers中配置router.go
package routers
import (
"github.com/astaxie/beego"
"testslim/controllers"
)
func init() {
beego.Router("/",&controllers.MainController{})
//beego.Router("/test",&controllers.TestController{})
beego.AutoRouter(&controllers.TestController{})
}
运用以上的操作可以完成一套简单的接口