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

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

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

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

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
    }
}

开源作品

GO-FLY,一套可私有化部署的免费开源客服系统,安装过程不超过五分钟(超过你打我 !),基于Golang开发,二进制文件可直接使用无需搭开发环境,下载zip解压即可,仅依赖MySQL数据库,是一个开箱即用的网页在线客服系统,致力于帮助广大开发者/中小站长快速整合私有客服功能
github地址:go-fly
官网地址:https://gofly.sopans.com
原文地址:https://www.cnblogs.com/taoshihan/p/15234760.html