选择beego是因为它文档比较全, 选择xorm是因为我用了很久,而且它真的很好用.
web应用中,用的最多的还是 json的请求和返回.
参考jas的风格, API的返回值,规定如下, 如果请求成功. 返回
{"error": null, "data": ...}
失败返回
{"error": "why failed..", "data": ...}
先假设有个struct叫User, 已经初始化 var x *xorm.Engine
type User struct {
ID int64 `json:"id" xorm:"id pk autoincr"`
Name string `json:"name"`
}
beego中的路由规则
beego.Router("/api/template/save", &controllers.UserController{}, "post:save")
beego.Router("/api/template/all", &controllers.UserController{}, "get:All")
beego.Router("/api/template/:id(\d+)", &controllers.UserController{}) // GET + PUT + DELETE
conf/app.conf中增加一行 autorender=false
APIController这个东西是从beego.Controller继承过来的东东.
type APIController struct {
beego.Controller
err error
data interface{}
}
// 函数结束时,组装成json结果返回
func (this *APIController) Finish() {
r := struct {
Error interface{} `json:"error"`
Data interface{} `json:"data"`
}{}
if this.err != nil {
r.Error = this.err.Error()
}
r.Data = this.data
this.Data["json"] = r
this.ServeJson()
}
// 如果请求的参数不存在,就直接 error返回
func (this *APIController) MustString(key string) string {
v := this.GetString(key)
if v == "" {
this.Data["json"] = map[string]string{
"error": fmt.Sprintf("require filed: %s", key),
"data": "orz!!",
}
this.ServeJson()
this.StopRun()
}
return v
}
// 其他的函数跟它累似,就不写了
Create + Update = Save
// for /api/user/create
func (v *User) Create() error {
_, err = x.Insert(v)
return err
}
// for /api/user/update
func UpdateUser(id int64, v *User) error {
affec, err := x.Id(id).Update(v)
if err == nil && affec == 0 {
err = errors.New("update user error")
}
return err
}
// for /api/user/save
func (v *User) Save() error {
if v.ID == 0 {
return v.Create()
}
return UpdateUser(id, v)
}
// for /api/user/all
func AllUser() (vs[]User, err error{
err = x.Find(&vs)
return
}
// for /api/user/delete
func DelUser(id int64) error {
affec, err := x.Id(id).Delete(new(User))
if err == nil && affec == 0 {
err = errors.New("already deleted")
}
this.err = err
}
type UserController struct {
APIController
}
// Save
func (this *UserController) Save() {
v := new(models.User)
v.ID = this.MustInt64WithDefault("id", 0)
v.Name = this.MustString("name")
this.err = v.Save()
}
// Put
func (this *UserController) Put(){
v := new(models.User)
v.ID = this.MustInt64(":id")
v.Name = this.MustString("name")
this.err = v.Save()
}
// All
func (this *UserController) All(){
this.data, this.err = models.AllUser()
}
// Delete
func (this *UserController) Delete(){
id := this.MustInt64(":id")
this.err = models.DeleteUser(id)
}