Skip to content

Latest commit

 

History

History
88 lines (64 loc) · 4.17 KB

README.md

File metadata and controls

88 lines (64 loc) · 4.17 KB

gowww i18n GoDoc Build Coverage Go Report Status Testing

Package i18n provides internationalization utilities.

Installing

  1. Get package:

    go get -u github.com/gowww/i18n
  2. Import it in your code with dependencies:

    import (
    	"github.com/gowww/i18n"
    	"golang.org/x/text/language"
    )

Usage

Make the Locales (string to string, for each language):

locales := i18n.Locales{
	language.English: {
		"hello": "Hello!",
	},
	language.French: {
		"hello": "Bonjour !",
	},
}

You're ready to make a handler with these locales, the default locale and the request parsers (matching the client language) you want to use.

Inside a handler, use RequestTranslator to get the translator containing the best locale for client.
Use Translator.T, Translator.THTML, Translator.Tn or Translator.TnHTML to retrieve the translation from a key.

i18n.RequestTranslator(r).T("hello")

So, to wrap an http.Handler, use Handle:

mux := http.NewServeMux()

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	rt := i18n.RequestTranslator(r)
	fmt.Fprint(w, rt.T("hello"))
})

http.ListenAndServe(":8080", i18n.Handle(mux, locales, language.English, i18n.ParseAcceptLanguage))

To wrap an http.HandlerFunc, use HandleFunc:

http.Handle("/", i18n.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
	rt := i18n.RequestTranslator(r)
	fmt.Fprint(w, rt.T("hello"))
}, locales, language.English, i18n.ParseAcceptLanguage))

http.ListenAndServe(":8080", nil)

Functioning

  1. The i18n handler receives a request.
  2. It must solve one question: what's the best locale for the user?
  3. To determine this, it has one or more Parsers (the ones you provided). They have their own way to find a result.
  4. So the i18n handler questions each parser (in the same order you provided them) and each one gives no, one or more potential locale.
  5. The i18n handler takes the first locale having a certains confidence threshold, adds a translator to the request context and serves your own handler.

References