1. 多语言翻译验证

当业务系统对验证信息有特殊需求时,例如:返回信息需要自定义,手机端返回的信息需要是中文而pc端发挥返回的信息需要时英文,如何做到请求一个接口满足上述三种情况。

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/go-playground/locales/en"
  6. "github.com/go-playground/locales/zh"
  7. "github.com/go-playground/locales/zh_Hant_TW"
  8. ut "github.com/go-playground/universal-translator"
  9. "gopkg.in/go-playground/validator.v9"
  10. en_translations "gopkg.in/go-playground/validator.v9/translations/en"
  11. zh_translations "gopkg.in/go-playground/validator.v9/translations/zh"
  12. zh_tw_translations "gopkg.in/go-playground/validator.v9/translations/zh_tw"
  13. )
  14. var (
  15. Uni *ut.UniversalTranslator
  16. Validate *validator.Validate
  17. )
  18. type User struct {
  19. Username string `form:"user_name" validate:"required"`
  20. Tagline string `form:"tag_line" validate:"required,lt=10"`
  21. Tagline2 string `form:"tag_line2" validate:"required,gt=1"`
  22. }
  23. func main() {
  24. en := en.New()
  25. zh := zh.New()
  26. zh_tw := zh_Hant_TW.New()
  27. Uni = ut.New(en, zh, zh_tw)
  28. Validate = validator.New()
  29. route := gin.Default()
  30. route.GET("/5lmh", startPage)
  31. route.POST("/5lmh", startPage)
  32. route.Run(":8080")
  33. }
  34. func startPage(c *gin.Context) {
  35. //这部分应放到中间件中
  36. locale := c.DefaultQuery("locale", "zh")
  37. trans, _ := Uni.GetTranslator(locale)
  38. switch locale {
  39. case "zh":
  40. zh_translations.RegisterDefaultTranslations(Validate, trans)
  41. break
  42. case "en":
  43. en_translations.RegisterDefaultTranslations(Validate, trans)
  44. break
  45. case "zh_tw":
  46. zh_tw_translations.RegisterDefaultTranslations(Validate, trans)
  47. break
  48. default:
  49. zh_translations.RegisterDefaultTranslations(Validate, trans)
  50. break
  51. }
  52. //自定义错误内容
  53. Validate.RegisterTranslation("required", trans, func(ut ut.Translator) error {
  54. return ut.Add("required", "{0} must have a value!", true) // see universal-translator for details
  55. }, func(ut ut.Translator, fe validator.FieldError) string {
  56. t, _ := ut.T("required", fe.Field())
  57. return t
  58. })
  59. //这块应该放到公共验证方法中
  60. user := User{}
  61. c.ShouldBind(&user)
  62. fmt.Println(user)
  63. err := Validate.Struct(user)
  64. if err != nil {
  65. errs := err.(validator.ValidationErrors)
  66. sliceErrs := []string{}
  67. for _, e := range errs {
  68. sliceErrs = append(sliceErrs, e.Translate(trans))
  69. }
  70. c.String(200, fmt.Sprintf("%#v", sliceErrs))
  71. }
  72. c.String(200, fmt.Sprintf("%#v", "user"))
  73. }

正确的链接:http://localhost:8080/testing?user_name=枯藤&tag_line=9&tag_line2=33&locale=zh

http://localhost:8080/testing?user_name=枯藤&tag_line=9&tag_line2=3&locale=en 返回英文的验证信息

http://localhost:8080/testing?user_name=枯藤&tag_line=9&tag_line2=3&locale=zh 返回中文的验证信息

查看更多的功能可以查看官网 gopkg.in/go-playground/validator.v9