golang web框架 beego 学习 (六) request body和module的映射
router.go
package routers import ( "gowebProject/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/users/user", &controllers.UserController{}, "Post:AddUser") }
myModules.go
package models import ( "fmt" "time" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" ) type User struct { Id int64 `json:"id"` //定义json中字段和module的映射关系 Name string `json:"name"` Email string `json:"email"` Age int64 `json:"age"` }
func CreateUser(user *User) {
o := orm.NewOrm()
if successNums, err := o.Insert(user); err != nil {
fmt.Println("insert fail.....")
} else {
fmt.Println("success inserted %d datas", successNums)
}
}
userController.go
func (this *UserController) AddUser() { var ob md.User //这是一个model,struct类型 body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据 json.Unmarshal(body, &ob) //解析二进制json,把结果放进ob中 // user := &md.User{Id: ob.UserName, Mobile: ob.Mobile} md.CreateUser(&ob) //这是添加用户函数 // if nil != err { // this.Data["json"] = map[string]interface{}{"result": false, "msg": err} // } else { // this.Data["json"] = map[string]interface{}{"result": true, "msg": "新增成功"} // } // this.Data["json"] = map[string]interface{}{"result": false, "msg": err} this.Data["json"] = ob this.ServeJSON() }