Golang Beego 处理http请求body

Golang Beego 处理http请求body

1. 解析参数

GetString(key string) string
GetStrings(key string) []string
GetInt(key string) (int64, error)
GetBool(key string) (bool, error)
GetFloat(key string) (float64, error)
//
func (this *MainController) Post() {
    id := this.Input().Get("id")
    intid, err := strconv.Atoi(id)
}

///
type user struct {
    Id    int         `form:"-"`
    Name  interface{} `form:"username"`
    Age   int         `form:"age"`
    Email string
}

func (this *MainController) Post() {
    u := user{}
    if err := this.ParseForm(&u); err != nil {
        //handle error
    }
}

2、解析Request Body

//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()
}
上一篇:2021 win10下beego的正确安装方法!!


下一篇:[beego学习] 表单文件上传