This example uses the LANG env var so these commands set it as courtesy.
LANG=zh_CN.UTF-8 go run main.go
格式错误
LANG=en_GB.UTF-8 go run main.go
Invalid email address
| package main | |
| import ( | |
| "fmt" | |
| "os" | |
| "github.com/asaskevich/govalidator" | |
| // my pretend module with some translation logic | |
| "github.com/my/translations" | |
| ) | |
| type person struct { | |
| Name string `valid:"-"` | |
| Email string `valid:"email~EMAIL_INVALID"` // email is not correct || email 格式错误 | |
| } | |
| func main() { | |
| translations.SetLocale("en_GB.UTF-8") | |
| p := person{Name: "clearcodecdn", Email: "jjj"} | |
| _, err := govalidator.ValidateStruct(p) | |
| if err != nil { | |
| localeAwareText := translations.Translate(err.Error()) | |
| fmt.Println(localeAwareText) | |
| return | |
| } | |
| // no validation errors | |
| fmt.Println("All OK") | |
| } | 
| package translations | |
| import ( | |
| "github.com/my/translations/en_gb" | |
| "github.com/my/translations/zh_CN" | |
| ) | |
| var locale string | |
| func SetLocale(myLocale string) { | |
| // checked against some whitelist | |
| locale = myLocale | |
| } | |
| func Translate(myStr string) (string, ok) { | |
| if locale == "en_GB.UTF-8" { | |
| // the particular translations could come from a file, a database, an API or whatever. | |
| translation, ok := en_gb.Lookup(myStr) | |
| } | |
| // etc, or a switch or something | |
| return translation, ok | |
| } |