Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request body validation

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?

like image 733
ligowsky Avatar asked Oct 29 '19 05:10

ligowsky


People also ask

Is @RequestBody mandatory?

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.

What is API request validation?

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.


1 Answers

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 "
}
like image 59
sh.seo Avatar answered Sep 21 '22 00:09

sh.seo