1 回答
TA贡献1830条经验 获得超9个赞
注册验证程序包:https://godoc.org/gopkg.in/validator.v2
// main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"gopkg.in/validator.v2"
)
type User struct {
Username string `json:"username" validate:"min=1,max=16,regexp=^[a-zA-Z]*$"`
Name string `json:"name" validate:"min=1,max=16"`
Password string `json:"password" validate:"min=1,max=16"`
}
func loginHandler(ctx *gin.Context) {
var user User
if err := ctx.ShouldBindJSON(&user); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
}
if err := validator.Validate(user); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
}
}
func main() {
r := gin.Default()
r.POST("/login", loginHandler)
r.Run()
}
请求:POST:本地主机:8080/登录
{
"username":"123123",
"name":"golang",
"password":"gin"
}
回复:
{
"error": "Username: regular expression mismatch "
}
- 1 回答
- 0 关注
- 121 浏览
添加回答
举报