I'm using gin to handle requests, but I'm having trouble validating data in a request body, e.g.
type User struct {
Username string `json:"username" binding:"required,min=1,max=16"`
Name string `json:"name" binding:"required,min=1,max=16"`
Password string `json:"password" binding:"required,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(),
})
}
How can I handle values with whitespaces like " username "
or " John Doe "
? As far as I know it's not possible to use regex in gin's validator.
What are the best practices or patterns for request body validation in Golang?
requestBody consists of the content object, an optional Markdown-formatted description , and an optional required flag ( false by default). content lists the media types consumed by the operation (such as application/json ) and specifies the schema for each media type. Request bodies are optional by default.
API validation is the process of checking to see if an API meets certain requirements for how it works, how well it performs, how safe it is, and other things. It is an important part of developing software because it helps make sure that an API meets the needs of its users and works as expected.
Reg validator package: 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()
}
Request: POST: localhost:8080/login
{
"username":"123123",
"name":"golang",
"password":"gin"
}
Response:
{
"error": "Username: regular expression mismatch "
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With