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