main.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package main
  2. import (
  3. "context"
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "time"
  8. "github.com/go-playground/locales"
  9. "github.com/go-playground/locales/currency"
  10. "github.com/go-playground/locales/en"
  11. "github.com/go-playground/locales/fr"
  12. "github.com/go-playground/pure"
  13. "github.com/go-playground/pure/examples/middleware/logging-recovery"
  14. "github.com/go-playground/universal-translator"
  15. )
  16. var (
  17. tmpls *template.Template
  18. utrans *ut.UniversalTranslator
  19. transKey = struct {
  20. name string
  21. }{
  22. name: "transKey",
  23. }
  24. )
  25. // Translator wraps ut.Translator in order to handle errors transparently
  26. // it is totally optional but recommended as it can now be used directly in
  27. // templates and nobody can add translations where they're not supposed to.
  28. type Translator interface {
  29. locales.Translator
  30. // creates the translation for the locale given the 'key' and params passed in.
  31. // wraps ut.Translator.T to handle errors
  32. T(key interface{}, params ...string) string
  33. // creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments
  34. // and param passed in.
  35. // wraps ut.Translator.C to handle errors
  36. C(key interface{}, num float64, digits uint64, param string) string
  37. // creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments
  38. // and param passed in.
  39. // wraps ut.Translator.O to handle errors
  40. O(key interface{}, num float64, digits uint64, param string) string
  41. // creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and
  42. // 'digit2' arguments and 'param1' and 'param2' passed in
  43. // wraps ut.Translator.R to handle errors
  44. R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) string
  45. // Currency returns the type used by the given locale.
  46. Currency() currency.Type
  47. }
  48. // implements Translator interface definition above.
  49. type translator struct {
  50. locales.Translator
  51. trans ut.Translator
  52. }
  53. var _ Translator = (*translator)(nil)
  54. func (t *translator) T(key interface{}, params ...string) string {
  55. s, err := t.trans.T(key, params...)
  56. if err != nil {
  57. log.Printf("issue translating key: '%v' error: '%s'", key, err)
  58. }
  59. return s
  60. }
  61. func (t *translator) C(key interface{}, num float64, digits uint64, param string) string {
  62. s, err := t.trans.C(key, num, digits, param)
  63. if err != nil {
  64. log.Printf("issue translating cardinal key: '%v' error: '%s'", key, err)
  65. }
  66. return s
  67. }
  68. func (t *translator) O(key interface{}, num float64, digits uint64, param string) string {
  69. s, err := t.trans.C(key, num, digits, param)
  70. if err != nil {
  71. log.Printf("issue translating ordinal key: '%v' error: '%s'", key, err)
  72. }
  73. return s
  74. }
  75. func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) string {
  76. s, err := t.trans.R(key, num1, digits1, num2, digits2, param1, param2)
  77. if err != nil {
  78. log.Printf("issue translating range key: '%v' error: '%s'", key, err)
  79. }
  80. return s
  81. }
  82. func (t *translator) Currency() currency.Type {
  83. // choose your own locale. The reason it isn't mapped for you is because many
  84. // countries have multiple currencies; it's up to you and you're application how
  85. // and which currencies to use. I recommend adding a function it to to your custon translator
  86. // interface like defined above.
  87. switch t.Locale() {
  88. case "en":
  89. return currency.USD
  90. case "fr":
  91. return currency.EUR
  92. default:
  93. return currency.USD
  94. }
  95. }
  96. func main() {
  97. en := en.New()
  98. utrans = ut.New(en, en, fr.New())
  99. setup()
  100. tmpls, _ = template.ParseFiles("home.tmpl")
  101. r := pure.New()
  102. r.Use(middleware.LoggingAndRecovery(true), translatorMiddleware)
  103. r.Get("/", home)
  104. log.Println("Running on Port :8080")
  105. log.Println("Try me with URL http://localhost:8080/?locale=en")
  106. log.Println("and then http://localhost:8080/?locale=fr")
  107. http.ListenAndServe(":8080", r.Serve())
  108. }
  109. func home(w http.ResponseWriter, r *http.Request) {
  110. // get locale translator ( could be wrapped into a helper function )
  111. t := r.Context().Value(transKey).(Translator)
  112. s := struct {
  113. Trans Translator
  114. Now time.Time
  115. PositiveNum float64
  116. NegativeNum float64
  117. Percent float64
  118. }{
  119. Trans: t,
  120. Now: time.Now(),
  121. PositiveNum: 1234576.45,
  122. NegativeNum: -35900394.34,
  123. Percent: 96.76,
  124. }
  125. if err := tmpls.ExecuteTemplate(w, "home", s); err != nil {
  126. log.Fatal(err)
  127. }
  128. }
  129. func translatorMiddleware(next http.HandlerFunc) http.HandlerFunc {
  130. return func(w http.ResponseWriter, r *http.Request) {
  131. // there are many ways to check, this is just checking for query param &
  132. // Accept-Language header but can be expanded to Cookie's etc....
  133. params := r.URL.Query()
  134. locale := params.Get("locale")
  135. var t ut.Translator
  136. if len(locale) > 0 {
  137. var found bool
  138. if t, found = utrans.GetTranslator(locale); found {
  139. goto END
  140. }
  141. }
  142. // get and parse the "Accept-Language" http header and return an array
  143. t, _ = utrans.FindTranslator(pure.AcceptedLanguages(r)...)
  144. END:
  145. // I would normally wrap ut.Translator with one with my own functions in order
  146. // to handle errors and be able to use all functions from translator within the templates.
  147. r = r.WithContext(context.WithValue(r.Context(), transKey, &translator{trans: t, Translator: t.(locales.Translator)}))
  148. next(w, r)
  149. }
  150. }
  151. func setup() {
  152. en, _ := utrans.FindTranslator("en")
  153. en.AddCardinal("days-left", "There is {0} day left", locales.PluralRuleOne, false)
  154. en.AddCardinal("days-left", "There are {0} days left", locales.PluralRuleOther, false)
  155. fr, _ := utrans.FindTranslator("fr")
  156. fr.AddCardinal("days-left", "Il reste {0} jour", locales.PluralRuleOne, false)
  157. fr.AddCardinal("days-left", "Il reste {0} jours", locales.PluralRuleOther, false)
  158. err := utrans.VerifyTranslations()
  159. if err != nil {
  160. log.Fatal(err)
  161. }
  162. }