depado / articles Goto Github PK
View Code? Open in Web Editor NEWArticles hosted on my blog
Home Page: https://blog.depado.eu
License: MIT License
Articles hosted on my blog
Home Page: https://blog.depado.eu
License: MIT License
This is the comment issue for the Buffer-less Multipart POST in Golang article.
This is the comment issue for the Dining Philosophers : Rust vs Go article.
This is the comment issue for the Scaffold a Flask Project article.
This is the comment issue for the DialogFlow : A complete guide with webhook article.
This is the comment issue for the Rendering the TOC with Blackfriday article.
This is the comment issue for the Small Example : How to use the scrape library in Go article.
This is the comment issue for the CI/CD with Drone, Kubernetes and Helm - Part 2 article.
This is the comment issue for the Cheap Open-Source Stack article.
This is the comment issue for the CI/CD with Drone, Kubernetes and Helm - Part 3 article.
This is the comment issue for the Smallblog Cheatsheet article.
This is the comment issue for the Setting up Caddy Server on Debian article.
This is the comment issue for the Embedding resources with rice.go in a Gin project article.
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.
This is the comment issue for the Cuite Playlists article.
This is the comment issue for the Gorm Gotchas article.
This is the comment issue for the Some Go snippets I find useful article.
This is the comment issue for the CI/CD with Drone, Kubernetes and Helm - Part 1 article.
This is the comment issue for the Smallblog Update & Capabilities article.
This is the comment issue for the Execute a function periodically using a wrapper in Python article.
This is the comment issue for the Mistune Syntax Highlighter, MathJax support and centered images article.
This is the comment issue for the Checklist for Go projects article.
This is the comment issue for the Dialogflow Webhook, Golang and Protobuf article.
This is the comment issue for the First Article article.
This is the comment issue for the Interesting Projects article.
This is the comment issue for the Gin Validation Errors Handling article.
This is the comment issue for the Closeable time ticker and multiple receivers in Go article.
This is the comment issue for the Writing a markov-chain IRC bot in Go article.
This is the comment issue for the QOR Admin Tutorial article.
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.
This is the comment issue for the Small and secure Docker images for Go article.
Hi,
github.com/namsral/flag
if you don't need a config file (config files are evil, see 12 factors)github.com/prometheus/client_golang/prometheus
). This is useful if your application is not a commandline toolI 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.
This is the comment issue for the Smallblog Documentation article.
This is the comment issue for the Play a distant audio stream using Go and Gstreamer article.
This is the comment issue for the Cheap Open-Source Stack article.
This is the comment issue for the Copy files and directories in Go article.
This is the comment issue for the Handle Dynamic Subdomains with Flask and Nginx article.
This is the comment issue for the DialogFlow : A complete guide article.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.