How to create a basic but flexible package validation in Golang?

I’m trying to build a package validation, but I’ve had some problems beacuse of the approach I have to take, until now I have the following:

`type Validator struct {
	err error
}`

func (v *Validator) IsEmpty(value string) bool {
 	if len(value) < 1 {
		v.err = fmt.Errorf("Campo obligatorio")
		return false
	}
	return true
}

// Keep creating more functions e.g Email, GreaterThan, Min, etc...

My approach is to attach functions to the validator struct such as IsEmpty and then use them with others structs, like so:

if !v.IsEmpty(c.Email) {
			fmt.Println(v.Error())
}

*Note: I need to support multiple languages, if you have a better idea or approach please let me know.

Not that your approach isn’t a good one to take, there is nothing wrong with it at all, but there are already several libraries available to aid in validation if you are interested.

1 Like

I have been playing with your package and I have a few questions:

1.- Right now there is only support for English language, if I need to support Spanish, French, and so on I have to create the translations?

2.- There is a way of exchanging between the different languages?, if so could you tell me a little about it

3.- Can I parse the messages into a json response?

I find your package so helpful, maybe I can ask you more information about how to implement it later thanks a lot.

I apologise for the long explanation in advance,

  1. By default I actually have no translations, it is completely optional; translations are actually a sort of plugin using universal-translator and need to be registered. you are correct that I have added, for pure convenience, some default English translations that can easily be registered but you can easily register translations for other languages as well, or even create your own English ones using RegisterTranslation. If desired you can create your own translation logic as well given that the validation errors returned have all the information necessary.

  2. If you mean changing from one language to another no, but you can generate the error message for multiple languages easily using the same validation error.

  3. yes you can parse the messages into a JSON response.

By all means you may reach out anytime :slight_smile: I already have an example of using the universal-translator with a website, adding a validation example into it should be pretty easy I’ll post a simple one file example here once finished.

@Gustavo_Diaz here is an example, it’s a modified version of this so please excuse the length and universal-translator specific logic, I would normally break up the logic into separate files and/or packages.

I know it does seem like allot of boilerplate for setting up translations, but you only have to ever do it once per language and then that logic is totally reusable in multiple applications.

package main

import (
	"context"
	"log"
	"net/http"

	"github.com/go-playground/locales"
	"github.com/go-playground/locales/currency"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/fr"
	"github.com/go-playground/pure"
	"github.com/go-playground/pure/examples/middleware/logging-recovery"
	"github.com/go-playground/universal-translator"
	"github.com/go-playground/validator"
)

var (
	transKey = struct {
		name string
	}{
		name: "transKey",
	}
)

// Translator wraps ut.Translator in order to handle errors transparently
// it is totally optional but recommended as it can now be used directly in
// templates and nobody can add translations where they're not supposed to.
type Translator interface {
	locales.Translator

	// creates the translation for the locale given the 'key' and params passed in.
	// wraps ut.Translator.T to handle errors
	T(key interface{}, params ...string) string

	// creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments
	//  and param passed in.
	// wraps ut.Translator.C to handle errors
	C(key interface{}, num float64, digits uint64, param string) string

	// creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments
	// and param passed in.
	// wraps ut.Translator.O to handle errors
	O(key interface{}, num float64, digits uint64, param string) string

	//  creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and
	//  'digit2' arguments and 'param1' and 'param2' passed in
	// wraps ut.Translator.R to handle errors
	R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) string

	// Currency returns the type used by the given locale.
	Currency() currency.Type

	// Base returns underlying ut.Translator vor external libs such as validator.
	Base() ut.Translator
}

// implements Translator interface definition above.
type translator struct {
	locales.Translator
	trans ut.Translator
}

var _ Translator = (*translator)(nil)

func (t *translator) T(key interface{}, params ...string) string {

	s, err := t.trans.T(key, params...)
	if err != nil {
		log.Printf("issue translating key: '%v' error: '%s'", key, err)
	}

	return s
}

func (t *translator) C(key interface{}, num float64, digits uint64, param string) string {

	s, err := t.trans.C(key, num, digits, param)
	if err != nil {
		log.Printf("issue translating cardinal key: '%v' error: '%s'", key, err)
	}

	return s
}

func (t *translator) O(key interface{}, num float64, digits uint64, param string) string {

	s, err := t.trans.C(key, num, digits, param)
	if err != nil {
		log.Printf("issue translating ordinal key: '%v' error: '%s'", key, err)
	}

	return s
}

func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) string {

	s, err := t.trans.R(key, num1, digits1, num2, digits2, param1, param2)
	if err != nil {
		log.Printf("issue translating range key: '%v' error: '%s'", key, err)
	}

	return s
}

func (t *translator) Currency() currency.Type {

	// choose your own locale. The reason it isn't mapped for you is because many
	// countries have multiple currencies; it's up to you and you're application how
	// and which currencies to use. I recommend adding a function it to to your custon translator
	// interface like defined above.
	switch t.Locale() {
	case "en":
		return currency.USD
	case "fr":
		return currency.EUR
	default:
		return currency.USD
	}
}

func (t *translator) Base() ut.Translator {
	return t.trans
}

type controller struct {
	UniTrans *ut.UniversalTranslator
	Validate *validator.Validate
}

func newController(utrans *ut.UniversalTranslator, validate *validator.Validate) *controller {
	return &controller{
		UniTrans: utrans,
		Validate: validate,
	}
}

func main() {

	validate := validator.New()

	en := en.New() // fallback locale
	utrans := ut.New(en, en, fr.New())
	setup(utrans, validate)

	controller := newController(utrans, validate)

	r := pure.New()
	r.Use(middleware.LoggingAndRecovery(true), newTranslatorMiddleware(utrans))
	r.Get("/", controller.home)

	log.Println("Running on Port :8080")
	log.Println("Try me with URL http://localhost:8080/?locale=en")
	log.Println("and then http://localhost:8080/?locale=fr")
	http.ListenAndServe(":8080", r.Serve())
}

func (app *controller) home(w http.ResponseWriter, r *http.Request) {

	// get locale translator ( could be wrapped into a helper function )
	t := r.Context().Value(transKey).(Translator)

	s := struct {
		Username string `validate:"required"`
		Age      uint8  `validate:"required"`
	}{
		Username: "",
		Age:      0,
	}

	errs := app.Validate.Struct(s)
	if errs != nil {
		verrs := errs.(validator.ValidationErrors)

		translated := verrs.Translate(t.Base())

		err := pure.JSON(w, http.StatusOK, translated)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}
}

func newTranslatorMiddleware(utrans *ut.UniversalTranslator) pure.Middleware {

	return func(next http.HandlerFunc) http.HandlerFunc {

		return func(w http.ResponseWriter, r *http.Request) {

			// there are many ways to check, this is just checking for query param &
			// Accept-Language header but can be expanded to Cookie's etc....

			params := r.URL.Query()

			locale := params.Get("locale")
			var t ut.Translator

			if len(locale) > 0 {

				var found bool

				if t, found = utrans.GetTranslator(locale); found {
					goto END
				}
			}

			// get and parse the "Accept-Language" http header and return an array
			t, _ = utrans.FindTranslator(pure.AcceptedLanguages(r)...)
		END:
			// I would normally wrap ut.Translator with one with my own functions in order
			// to handle errors and be able to use all functions from translator within the templates.
			r = r.WithContext(context.WithValue(r.Context(), transKey, &translator{trans: t, Translator: t.(locales.Translator)}))

			next(w, r)
		}
	}
}

func setup(utrans *ut.UniversalTranslator, validate *validator.Validate) {

	en, _ := utrans.FindTranslator("en")
	en.AddCardinal("days-left", "There is {0} day left", locales.PluralRuleOne, false)
	en.AddCardinal("days-left", "There are {0} days left", locales.PluralRuleOther, false)

	// en validation translations
	validate.RegisterTranslation("required", en,
		func(ut ut.Translator) (err error) {

			if err = ut.Add("required", "Is a required field", false); err != nil {
				return
			}

			return

		},
		func(ut ut.Translator, fe validator.FieldError) string {

			t, err := ut.T(fe.Tag())
			if err != nil {
				log.Printf("warning: error translating FieldError: %#v", fe)
				return fe.(error).Error()
			}

			return t
		})

	fr, _ := utrans.FindTranslator("fr")
	fr.AddCardinal("days-left", "Il reste {0} jour", locales.PluralRuleOne, false)
	fr.AddCardinal("days-left", "Il reste {0} jours", locales.PluralRuleOther, false)

	// fr validation translations
	validate.RegisterTranslation("required", fr,
		func(ut ut.Translator) (err error) {

			if err = ut.Add("required", "Un champ obligatoire", false); err != nil {
				return
			}

			return

		},
		func(ut ut.Translator, fe validator.FieldError) string {

			t, err := ut.T(fe.Tag())
			if err != nil {
				log.Printf("warning: error translating FieldError: %#v", fe)
				return fe.(error).Error()
			}

			return t
		})

	err := utrans.VerifyTranslations()
	if err != nil {
		log.Fatal(err)
	}
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.