go-playground-converter is formatter error response inspiration like express-validator in nodejs build on top go-playground-validator.

Go Playground Converter

GitHub go.mod Go version GitHub GitHub issues GitHub closed issues GitHub contributors

go-playground-converter is formatter error response inspiration like express-validator in nodejs build on top in go-playground-validator, see more about struct reference follow this.

Installation

$ go get -u github.com/restuwahyu13/go-playground-converter

Function Reference

Method Name Description
NewValidator wrapper struct validation schema for go playground validator
NewBindValidator change the struct to an error response
BindValidator for returning error response

Struct Reference

Struct Name Description
ErrorConfig config for creating error message
ErrorMetaConfig meta config defination for returning error response

Example Usage

  • Example Usage With Frmework

    package main
    
    import (
      "net/http"
    
      "github.com/gin-gonic/gin"
    
      "github.com/go-playground/validator/v10"
      gpc "github.com/restuwahyu13/go-playground-converter"
    )
    
    type User struct {
      Fullname string `validate:"required,lowercase"`
      Email string `validate:"required,email"`
      Password string `validate:"required,gte=8"`
    }
    
    func main() {
      router := gin.Default()
      router.POST("/", func(ctx *gin.Context) {
    
        var input User
        ctx.ShouldBindJSON(&input)
    
        var validate *validator.Validate
        validators := gpc.NewValidator(validate)
        bind := gpc.NewBindValidator(validators)
    
        config := gpc.ErrorConfig{
          Options: []gpc.ErrorMetaConfig{
              gpc.ErrorMetaConfig{
                Tag: "required",
                Field: "Fullname",
                Message: "fullname is required",
              },
              gpc.ErrorMetaConfig{
                Tag: "lowercase",
                Field: "Fullname",
                Message: "fullname must be a lowercase",
              },
              gpc.ErrorMetaConfig{
                Tag: "required",
                Field: "Email",
                Message: "email is required",
              },
              gpc.ErrorMetaConfig{
                Tag: "email",
                Field: "Email",
                Message: "email format is not valid",
              },
              gpc.ErrorMetaConfig{
                Tag: "required",
                Field: "Password",
                Message: "password is required",
              },
              gpc.ErrorMetaConfig{
                Tag: "gte",
                Field: "Password",
                Message: "password must be greater 7",
              },
            },
          }
    
          errResponse, errCount := bind.BindValidator(&input, config.Options)
    
          if errCount > 0 {
            ctx.JSON(http.StatusBadRequest, errResponse)
            ctx.AbortWithStatus(http.StatusBadRequest)
            return
          } else {
            ctx.JSON(http.StatusOk, gin.H{"message": "register new account successfully"})
          }
      })
    
      router.Run(":3000")
    }
      // error response like this
      //   {
      //     "results": {
      //         "errors": [
      //             {
      //                 "Fullname": {
      //                     "message": "fullname must be a lowercase",
      //                     "value": "Restu Wahyu Saputra",
      //                     "param": "Fullname",
      //                     "tag": "lowercase"
      //                 }
      //             },
      //             {
      //                 "Email": {
      //                     "message": "email format is not valid",
      //                     "value": "restuwahyu13@#gmail.com",
      //                     "param": "Email",
      //                     "tag": "email"
      //                 }
      //             },
      //             {
      //                 "Password": {
      //                     "message": "password must be greater 7",
      //                     "value": "qwerty",
      //                     "param": "Password",
      //                     "tag": "gte"
      //                 }
      //             }
      //         ]
      //     }
      // }
  • Example Usage With No Framework

    package main
    
    import (
      "fmt"
    
      "github.com/go-playground/validator/v10"
      gpc "github.com/restuwahyu13/go-playground-converter/utils"
    )
    
    type User struct {
      Fullname string `validate:"required,lowercase"`
      Email string `validate:"required,email"`
      Password string `validate:"required,gte=8"`
    }
    
    func main() {
    
      var input User
      var validate *validator.Validate
      validators := gpc.NewValidator(validate)
      bind := gpc.NewBindValidator(validators)
    
      input.Fullname = "Restu Wahyu Saputra"
      input.Email = "restuwahyu13@#zetmail.com"
      input.Password = "qwerty"
    
      config := gpc.ErrorConfig{
        Options: []gpc.ErrorMetaConfig{
            gpc.ErrorMetaConfig{
              Tag: "required",
              Field: "Fullname",
              Message: "fullname is required",
            },
            gpc.ErrorMetaConfig{
              Tag: "lowercase",
              Field: "Fullname",
              Message: "fullname must be a lowercase",
            },
            gpc.ErrorMetaConfig{
              Tag: "required",
              Field: "Email",
              Message: "email is required",
            },
            gpc.ErrorMetaConfig{
              Tag: "email",
              Field: "Email",
              Message: "email format is not valid",
            },
            gpc.ErrorMetaConfig{
              Tag: "required",
              Field: "Password",
              Message: "password is required",
            },
            gpc.ErrorMetaConfig{
              Tag: "gte",
              Field: "Password",
              Message: "password must be greater 7",
            },
          },
        }
    
      errResponse, errCount := bind.BindValidator(&input, config.Options)
    
      if errCount > 0 {
        fmt.Println(errResponse)
      } else {
        fmt.Println("not error found")
      }
    }
      // error response like this
      //   {
      //     "results": {
      //         "errors": [
      //             {
      //                 "Fullname": {
      //                     "message": "fullname must be a lowercase",
      //                     "value": "Restu Wahyu Saputra",
      //                     "param": "Fullname",
      //                     "tag": "lowercase"
      //                 }
      //             },
      //             {
      //                 "Email": {
      //                     "message": "email format is not valid",
      //                     "value": "restuwahyu13@#gmail.com",
      //                     "param": "Email",
      //                     "tag": "email"
      //                 }
      //             },
      //             {
      //                 "Password": {
      //                     "message": "password must be greater 7",
      //                     "value": "qwerty",
      //                     "param": "Password",
      //                     "tag": "gte"
      //                 }
      //             }
      //         ]
      //     }
      // }

Custom Usage

package util

import (
  "github.com/go-playground/validator/v10"
  gpc "github.com/restuwahyu13/go-playground-converter"
)


func GoValidator(s interface{}, config []gpc.ErrorMetaConfig) (interface{}, int) {
    var validate *validator.Validate
    validators := gpc.NewValidator(validate)
    bind := gpc.NewBindValidator(validators)

    errResponse, errCount := bind.BindValidator(s, config)
    return errResponse, errCount
}

Bugs

For information on bugs related to package libraries, please visit here

Contributing

Want to make Go Playground Converter more perfect ? Let's contribute and follow the contribution guide.

License

BACK TO TOP

Owner
Restu Wahyu Saputra
A bright future will come, just waiting times, someday I will definitely become a software engineer
Restu Wahyu Saputra
Similar Resources

Typo/error resilient, human-readable token generator

toktok A human-friendly token generator Creates tokens which avoid characters that can be easily misinterpreted, like '1' and 'I' or '8' and 'B', as w

Sep 16, 2022

Example of using advanced gRPC error model

grpcerrors Example of using advanced gRPC error model

Nov 19, 2021

Example app using labstack/echo and ozzo-validator.

Example app using labstack/echo and ozzo-validator.

Oct 17, 2022

Colorize (highlight) `go build` command output

Colorize (highlight) `go build` command output

colorgo colorgo is a wrapper to go command that colorizes output from go build and go test. Installation go get -u github.com/songgao/colorgo Usage c

Dec 18, 2022

James is your butler and helps you to create, build, debug, test and run your Go projects

James is your butler and helps you to create, build, debug, test and run your Go projects

go-james James is your butler and helps you to create, build, debug, test and run your Go projects. When you often create new apps using Go, it quickl

Oct 8, 2022

Build for all Go-supported platforms by default, disable those which you don't want.

bagop Build for all Go-supported platforms by default, disable those which you don't want. Overview bagop is a simple build tool for Go which tries to

Jul 29, 2022

Analyze the binary outputted by `go build` to get type information etc.

Analyze the binary outputted by go build to get type information etc.

Oct 5, 2022

Build reply markup keyboards easier than ever.

gotgbot keyboard Build reply markup keyboards easier than ever.

Feb 24, 2022

Build the brains of a vending machine with golang

Vending Machine Kata In this exercise you will build the brains of a vending machine. It will accept money, make change, maintain inventory, and dispe

Jan 7, 2022
Comments
  • Project description

    Project description

    You have Formatter error response inspiration like express-validator in nodejs build on top go-playground-validator as your description, but go-playground-converter as the title.

    Can you share a bit about this project and what it does?

    I'm doing a quick check for Awesome Indonesia.

Esfmt - An opinionated, zero-configuration formatter for ES/TS/ESX/TSX

esfmt - an opinionated, zero-configuration formatter for ES/TS/ESX/TSX Status: t

Apr 5, 2022
CodePlayground is a playground tool for go and rust language.

CodePlayground CodePlayground is a playground tool for go and rust language. Installation Use homebrews to install code-playground. brew tap trendyol/

Mar 5, 2022
Playground With Golang

playground-go required environment variables set the following environment variables for service runtime env var name value type PORT_NUMBER string ho

Jan 16, 2022
PCM converter - Resample part relies on SOXR.

Resample part relies on SOXR. To install make sure you have libsoxr installed, then run: go get -u github.com/ZhangJYd/pcm_convertor example: package

Nov 23, 2021
Serial to Keyboard converter for Polar's card readers

polar-serial-to-keyboard Serial to Keyboard converter for Polar's card readers Configuration This program is intended to be run as a background proces

Dec 17, 2021
Numtow - Golang number to words converter

numtow golang library to convert number to words. Supported languages: kazakh, e

Dec 31, 2022
T80nxbt - Thurastmaster-T80 to ProCon Converter

t80nxbt Thurastmaster-T80 to ProCon Converter. connection T80----usb----Raspberr

Jan 30, 2022
Protocol Buffers to HTTP client code generator/converter

Proto2http Proto2http provides a code generation tool to convert your protocol buffers (.proto) files into invokable HTTP request. Usage proto2http -p

Oct 23, 2022
Generate random, pronounceable, sometimes even memorable, "superhero like" codenames - just like Docker does with container names.

Codename an RFC1178 implementation to generate pronounceable, sometimes even memorable, "superheroe like" codenames, consisting of a random combinatio

Dec 11, 2022
Phalanx is a cloud-native full-text search and indexing server written in Go built on top of Bluge that provides endpoints through gRPC and traditional RESTful API.

Phalanx Phalanx is a cloud-native full-text search and indexing server written in Go built on top of Bluge that provides endpoints through gRPC and tr

Dec 25, 2022