Created
January 24, 2020 09:07
-
-
Save mehran-prs/c331c07d86155788b3a9f116933716ff to your computer and use it in GitHub Desktop.
Go ozzo-validation translator (using ozzo-validatlion v4 and above)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "github.com/go-ozzo/ozzo-validation/v4" | |
// Translator is the interface that need to be implemented if we | |
// need to error translation feature. | |
type Translator interface { | |
TranslateStructFieldErr(field string, err validation.Error) (string, error) | |
TranslateSingleFieldErr(err validation.Error) (string, error) | |
} | |
// Translate get a translator that must implemented Translator and | |
// return translated errors. | |
func Translate(e validation.Error, t Translator) (string, error) { | |
return t.TranslateSingleFieldErr(e) | |
} | |
// Translate function recursively translate all ozzo-validtion errors. | |
func TranslateErrors(es validation.Errors, t Translator) (map[string]interface{}, error) { | |
var errCollection = make(map[string]interface{}) | |
var err error | |
for k, e := range es { | |
if errors, ok := e.(validation.Errors); ok { | |
errCollection[k], err = TranslateErrors(errors, t) | |
if err != nil { | |
return nil, err | |
} | |
} else if ve, ok := e.(validation.Error); ok { | |
errCollection[k], err = t.TranslateStructFieldErr(k, ve) | |
if err != nil { | |
return nil, err | |
} | |
} else { | |
errCollection[k] = e | |
} | |
} | |
return errCollection, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment