binderr

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2020 License: MIT Imports: 1 Imported by: 0

README

binderr

package main

import (
    "errors"
    "github.com/gin-gonic/gin"
    "github.com/lohanx/binderr"
    "net/http"
)

var msgErrors = map[string]map[string]error{
    "name":{
        "required":errors.New("name is required"),
    },
    "email":{
        "required":errors.New("email is required"),
        "email":errors.New("email format error"),
    },
}

type Person struct {
    Name string `form:"name" binding:"required"`
    Email string `form:"email" binding:"required,email"`
}

func main() {
    router := gin.New()
    router.GET("/get-person",func(ctx *gin.Context){
        var person Person
        if err := ctx.ShouldBind(&person);err != nil {
            ctx.JSON(http.StatusBadRequest,gin.H{
                "code":-1,
                "err":binderr.New(err,msgErrors).FirstError().Error(),
            })
            return
        }
        ctx.JSON(http.StatusOK,gin.H{
            "code":0,
            "data":person,
        })
    })
    router.Run("127.0.0.1:8080")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BindErrors

type BindErrors struct {
	// contains filtered or unexported fields
}

func New

func New(errors error, messages map[string]map[string]error) *BindErrors

errors gin build error messages are custom error messages

type Person struct {
    Email `form:"email" binding:"required,email"`
    Password `form:"password" binding:"required,min=8"`
}
var messages = map[string]map[string]error{
    "Email":{
        "required":errors.New("error"),
        "email":errors.New("error"),
    },
    "Password":{
        "required":errors.New("error"),
        "min":errors.New("error"),
    },
}

func (*BindErrors) Errors

func (be *BindErrors) Errors() []error

Errors return all errors

func (*BindErrors) FirstError

func (be *BindErrors) FirstError() error

FirstError return the first error

func (*BindErrors) GetFiledErrors added in v0.0.2

func (be *BindErrors) GetFiledErrors(field string) []error

GetErrors return all errors of the field

func (*BindErrors) GetTagError added in v0.0.2

func (be *BindErrors) GetTagError(field, tag string) error

GetError return error based on field and tag

func (*BindErrors) LastError

func (be *BindErrors) LastError() error

LastError return the last error

func (*BindErrors) Len added in v0.0.2

func (be *BindErrors) Len() int

Len return errors length

Jump to

Keyboard shortcuts

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