Giter Club home page Giter Club logo

articles's Issues

about your GO program checklist

Hi,

  • viper can be replaced by the simplest github.com/namsral/flag if you don't need a config file (config files are evil, see 12 factors)
  • dep is "deprecated", use modules
  • cobra have a strong application layout which makes your go code far less readable
  • you forgot to add metrics (using the prometheus endpoint and github.com/prometheus/client_golang/prometheus). This is useful if your application is not a commandline tool
  • you forgot to add tracing, which can also be helpful if it's not a commandline. Opentracing, Jaeger, Zipkin... or Opencensu which offer all of the above plus many other things

I would have commented on the blog directly, but your oauth tool against Github is requesting read and write to all my public repos, which is not going to happen.

gin-validation for an array of struct

Hi @depado ,
Greetings, I saw your blog for gin-validation and it helped in my use case.
But I am unable to use it if the validation is done on an array of struct.

My sample code

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"reflect"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

type User struct {
	Email string `json:"email" form:"e-mail" binding:"required"`
	Name  string `json:"name" binding:"required"`
}

func main() {
	route := gin.Default()
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})
	}
	route.POST("/user", validateUser)
	route.Run(":8085")
}
func validateUser(c *gin.Context) {
	var u []User
	if err := c.ShouldBindJSON(&u); err == nil {
		c.JSON(http.StatusOK, gin.H{"message": "User validation successful."})
	} else {
		fmt.Println(err)
		var verr validator.ValidationErrors
		var jsErr *json.UnmarshalTypeError

		if errors.As(err, &verr) {
			c.JSON(http.StatusBadRequest, gin.H{"errors": Descriptive(verr)})
			return
		} else if errors.As(err, &jsErr) {
			c.JSON(http.StatusBadRequest, gin.H{"errors": MarshalErr(*jsErr)})
			return
		}
	}
}

func Simple(verr validator.ValidationErrors) map[string]string {
	errs := make(map[string]string)
	for _, f := range verr {
		err := f.ActualTag()

		if f.Param() != "" {
			err = fmt.Sprintf("%s=%s", err, f.Param())
		}
		errs[f.Field()] = err + "," + f.Kind().String()
		fmt.Println(errs)
	}
	return errs

}

type ValidationError struct {
	Field  string `json:"field"`
	Type   string `json:"type"`
	Reason string `json:"reason"`
}
func MarshalErr(jsErr json.UnmarshalTypeError) ValidationError {
	errs := ValidationError{}
	errs.Field=jsErr.Field
	errs.Reason="invalid type"
	errs.Type=jsErr.Type.String()
	return errs
}
func Descriptive(verr validator.ValidationErrors) []ValidationError {
	errs := []ValidationError{}

	for _, f := range verr {
		fmt.Println(f)
		err := f.ActualTag()
		if f.Param() != "" {
			err = fmt.Sprintf("%s=%s", err, f.Param())
		}
		errs = append(errs, ValidationError{Field: f.Field(), Reason: err, Type: f.Type().Name()})
	}

	return errs
}

Test Input

curl --location --request POST 'http://localhost:8085/user' \
--header 'content-type: application/json' \
--data-raw '[
    {
        "email": "[email protected]",
        "name": "Me"
    },
    {
        "email": "[email protected]"
    }
]'

Expected output

"errors": [
        {
            "field": "name",
            "type": "string",
            "reason": "required"
        }
    ]

Can you please help me with it.

How to do gin-validation for an array of struct

Hi @depado ,
Greetings, I saw your blog for gin-validation and it helped in my use case.
But I am unable to use it if the validation is done on an array of struct.

My sample code

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"reflect"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

type User struct {
	Email string `json:"email" form:"e-mail" binding:"required"`
	Name  string `json:"name" binding:"required"`
}

func main() {
	route := gin.Default()
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})
	}
	route.POST("/user", validateUser)
	route.Run(":8085")
}
func validateUser(c *gin.Context) {
	var u []User
	if err := c.ShouldBindJSON(&u); err == nil {
		c.JSON(http.StatusOK, gin.H{"message": "User validation successful."})
	} else {
		fmt.Println(err)
		var verr validator.ValidationErrors
		var jsErr *json.UnmarshalTypeError

		if errors.As(err, &verr) {
			c.JSON(http.StatusBadRequest, gin.H{"errors": Descriptive(verr)})
			return
		} else if errors.As(err, &jsErr) {
			c.JSON(http.StatusBadRequest, gin.H{"errors": MarshalErr(*jsErr)})
			return
		}
	}
}

func Simple(verr validator.ValidationErrors) map[string]string {
	errs := make(map[string]string)
	for _, f := range verr {
		err := f.ActualTag()

		if f.Param() != "" {
			err = fmt.Sprintf("%s=%s", err, f.Param())
		}
		errs[f.Field()] = err + "," + f.Kind().String()
		fmt.Println(errs)
	}
	return errs

}

type ValidationError struct {
	Field  string `json:"field"`
	Type   string `json:"type"`
	Reason string `json:"reason"`
}
func MarshalErr(jsErr json.UnmarshalTypeError) ValidationError {
	errs := ValidationError{}
	errs.Field=jsErr.Field
	errs.Reason="invalid type"
	errs.Type=jsErr.Type.String()
	return errs
}
func Descriptive(verr validator.ValidationErrors) []ValidationError {
	errs := []ValidationError{}

	for _, f := range verr {
		fmt.Println(f)
		err := f.ActualTag()
		if f.Param() != "" {
			err = fmt.Sprintf("%s=%s", err, f.Param())
		}
		errs = append(errs, ValidationError{Field: f.Field(), Reason: err, Type: f.Type().Name()})
	}

	return errs
}

Test Input

curl --location --request POST 'http://localhost:8085/user' \
--header 'content-type: application/json' \
--data-raw '[
    {
        "email": "[email protected]",
        "name": "Me"
    },
    {
        "email": "[email protected]"
    }
]'

Expected output

"errors": [
        {
            "field": "name",
            "type": "string",
            "reason": "required"
        }
    ]

Can you please help me with it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.