gin框架的数据验证


用gin框架的数据验证,可以不用解析数据,减少if else,会简洁许多。

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)
type Example struct{
    Name string `form:"name" binding:"required" `//1。required表示该参数是必要参数,如果不传或为空会报错
    Age  int    `form:"age" `                    //2。如果用户输入数据类型不匹配会报错
    Sex  string `form:"sex"`
}

func get(c *gin.Context){
    var data Example
    //结构体只和查询参数绑定
    if err:=c.ShouldBindQuery(&data);err==nil{
        fmt.Println(data.Name)
        fmt.Println(data.Age)
        fmt.Println(data.Sex)
        c.JSON(http.StatusOK,gin.H{"res":"success"})
    }else{
        fmt.Println(err.Error())
        c.JSON(http.StatusOK,gin.H{"res":err.Error()})
    }
}

func post(c *gin.Context){
    var data Example
    //结构体和传进来的json绑定
    if err:=c.ShouldBindJSON(&data);err==nil{
        fmt.Println(data.Name)
        fmt.Println(data.Age)
        fmt.Println(data.Sex)
        c.JSON(http.StatusOK,gin.H{"res":"success"})//gin.h()返回map[string]interface{}类型,返回数据这块也可以将结构体类型返回
    }else{
        fmt.Println(err.Error())
        c.JSON(http.StatusOK,gin.H{"res":err.Error()})
    }
}

func main(){
    router:=gin.Default()

    router.GET("/v1",get)
    router.POST("/v1",post)

    router.Run("127.0.0.1:8888")
}
//1。输入:
{
    "name":"zh"
    "age":18,
    "sex":"sex"
}
//输出:
zh
18
sex

//2。输入
{
    "name":"",
    "age":18,
    "sex":"sex"
}
//输出
{
    "res": "Key: 'Example.Name' Error:Field validation for 'Name' failed on the 'required' tag"
}

//3。输入
{
    "name":18,
    "age":18,
    "sex":"sex"
}
//输出
{
    "res": "json: cannot unmarshal number into Go struct field Example.Name of type string"
}
 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM