[Go] go语言gin框架验证post传递json数据

2021-09-08 14:51:45 浏览数 (1)

gin框架有获取并验证post的数据的功能

可以参考下面这段代码,兼容form数据和json数据

代码语言:javascript复制
type RegisterForm struct {
    Username   string `form:"username" json:"username" uri:"username" xml:"username" binding:"required"`
    Password   string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
    RePassword string `form:"rePassword" json:"rePassword" uri:"rePassword" xml:"rePassword" binding:"required"`
    Nickname   string `form:"nickname" json:"nickname" uri:"nickname" xml:"nickname" binding:"required"`
    Captcha    string `form:"captcha" json:"captcha" uri:"captcha" xml:"captcha" binding:"required"`
}

func PostUcRegister(c *gin.Context) {
    var form RegisterForm
    if err := c.Bind(&form); err != nil {
        c.JSON(200, gin.H{
            "code":   types.ApiCode.FAILED,
            "msg":    types.ApiCode.GetMessage(types.ApiCode.INVALID),
            "result": err.Error(),
        })
        return
    }
    c.JSON(200, gin.H{
        "code": types.ApiCode.SUCCESS,
        "msg":  types.ApiCode.GetMessage(types.ApiCode.SUCCESS),
    })
}

api_code.go

代码语言:javascript复制
package types

type Codes struct {
    SUCCESS   uint
    FAILED    uint
    INVALID   uint
    CnMessage map[uint]string
    EnMessage map[uint]string
    LANG      string
}

var ApiCode = &Codes{
    SUCCESS: 20000,
    FAILED:  40000,
    INVALID: 40001,
    LANG:    "cn",
}

func init() {
    ApiCode.CnMessage = map[uint]string{
        ApiCode.SUCCESS: "操作成功",
        ApiCode.FAILED:  "操作失败",
        ApiCode.INVALID: "参数错误",
    }
    ApiCode.EnMessage = map[uint]string{
        ApiCode.SUCCESS: "succeed",
        ApiCode.FAILED:  "failed",
        ApiCode.INVALID: "invalid params",
    }
}
func (c *Codes) GetMessage(code uint) string {
    if c.LANG == "cn" {
        message, ok := c.CnMessage[code]
        if !ok {
            return ""
        }
        return message
    } else {
        message, ok := c.EnMessage[code]
        if !ok {
            return ""
        }
        return message
    }
}

0 人点赞