validator

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2024 License: MIT Imports: 3 Imported by: 0

README

validator

gin request parameter check library.


Example of use

package main

import (
    "net/http"

    "gitee.com/the_sun_light/common_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"`
	Limit int    `json:"limit" form:"limit" binding:"gte=1"`
	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

Overview

Package validator is gin request parameter check library.

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