validator

package
v1.3.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2023 License: MIT Imports: 3 Imported by: 1

README

validator

gin request parameter check library.


Example of use

package main

import (
    "net/http"

    "github.com/zhufuyi/sponge/pkg/gin/validator"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
)

func main() {
	r := gin.Default()
	binding.Validator = validator.Init()
	
	r.Run(":8080")
}

type createUserRequest struct {
	Name  string `json:"name" form:"name" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
	Age   int    `json:"age" form:"age" binding:"gte=0,lte=120"`
	Email string `json:"email" form:"email" binding:"email"`
}

func CreateUser(c *gin.Context) {
	form := &createUserRequest{}
	err := c.ShouldBindJSON(form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"msg": "ok"})
}

type getUserRequest struct {
	Page int    `json:"page" form:"page" binding:"gte=0"`
	Size int    `json:"size" form:"size" binding:"gt=0"`
	Sort string `json:"sort" form:"sort" binding:"-"`
}

func GetUsers(c *gin.Context) {
	form := &getUserRequest{}
	err := c.ShouldBindQuery(form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
		return
	}

	users, err := getUsers(form)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
        return
    }

	c.JSON(http.StatusOK, gin.H{"users": users})
}

func getUsers(req *getUserRequest) ([]User,error){}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CustomValidator

type CustomValidator struct {
	Once     sync.Once
	Validate *valid.Validate
}

CustomValidator Custom valid objects

func Init

func Init() *CustomValidator

Init request body file valid

func NewCustomValidator

func NewCustomValidator() *CustomValidator

NewCustomValidator Instantiate

func (*CustomValidator) Engine

func (v *CustomValidator) Engine() interface{}

Engine Instantiate valid

func (*CustomValidator) ValidateStruct

func (v *CustomValidator) ValidateStruct(obj interface{}) error

ValidateStruct Instantiate struct valid

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL