• gin validator验证


    gin validator验证

    package main
    
    import (
    	"fmt"
    	"net/http"
    
    	"github.com/gin-gonic/gin"
    )
    
    type RegisterRequest struct {
    	Username string `json:"username" binding:"required"`
    	Nickname string `json:"nickname" binding:"required"`
    	Email    string `json:"email" binding:"required"`
    	Password string `json:"password" binding:"required"`
    	Age      uint8  `json:"age" binding:"gte=1,lte=120"`
    }
    
    func main() {
    
    	router := gin.Default()
    
    	router.POST("register", Register)
    
    	router.Run(":9999")
    }
    
    func Register(c *gin.Context) {
    	var r RegisterRequest
    	err := c.ShouldBindJSON(&r)
    	if err != nil {
    		fmt.Println("register failed")
    		c.JSON(http.StatusOK, gin.H{"msg": err.Error()})
    		return
    	}
    	fmt.Println("register success")
    	c.JSON(http.StatusOK, "successful")
    }
    
    

    错误验证

    测试:
    curl --location --request POST 'http://localhost:9999/register' 
    --header 'Content-Type: application/json' 
    --data-raw '{
        "username": "asong",
        "nickname": "golang梦工厂",
        "email": "7418.com",
        "password": "123",
        "age": 140
    }'
    

    成功的测试:

    curl --location --request POST 'http://localhost:9999/register' 
    --header 'Content-Type: application/json' 
    --data-raw '{
        "username":"jone",
        "nickname": "golang梦工厂",
        "email": "7418@qq.com",
        "password": "a123",
        "age": 80
    }'
    

    相关链接

    https://juejin.im/post/6863765115456454664

    【励志篇】: 古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
  • 相关阅读:
    梦断代码阅读笔记
    程序员的自我修养阅读笔记
    11月总结3
    11月总结3
    程序员的自我修养阅读笔记
    程序员的自我修养阅读笔记
    程序员的自我修养阅读笔记
    程序员的自我修养阅读笔记
    第十四周总结
    第十三周总结
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/13899200.html
Copyright © 2020-2023  润新知