router.gogit
package routers import ( "gowebProject/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/users/user", &controllers.UserController{}, "Post:AddUser") }
myModules.gogithub
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.goweb
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() }