Documentation ¶
Overview ¶
Package lang provides utilities for translating web services.
The Path function and the Languages type help you to follow Google's advice to use "different URLs for each language version of a page rather than using cookies or browser settings to adjust the content language on the page", using the "Subdirectories with gTLD" URL structure where localized URLs start with e.g. "/en/".
Generate translations with:
gotext-update-templates -srclang=en-US -lang=de-DE,en-US -out=catalog.go .
Then use them in your code:
langs := lang.MakeLanguages(nil, "de", "en") for _, l := range langs { http.HandleFunc("/"+l.Prefix, func(w http.ResponseWriter, r *http.Request) { l, _, _ := langs.FromPath(r) l.Printer.Fprintf(w, "Hello World") }) } http.HandleFunc("/", langs.Redirect)
As in the example, adding routes for each language is recommended over using route parameters with possibly conflicting rules.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Lang ¶
func (Lang) Collator ¶
Collator creates a case-insensitive collator for l.Tag. The collator is not stored in Lang because it is not thread-safe (see https://github.com/golang/go/issues/57314).
type Languages ¶
type Languages []Lang
func MakeLanguages ¶
MakeLanguages takes a list of URL path prefixes used in your application (e. g. "de", "en") in the alphabetical order of the dictionary keys in the catalog. If catalog is nil, then message.DefaultCatalog is used. MakeLanguages panics if len(prefixes) does not equal the number of languages in the catalog.
func (Languages) FromPath ¶
FromPath returns the language whose prefix matches the first segment of r.URL.Path and the remaining path. If no language matches, it returns langs[0], the full path and false.
func (Languages) RedirectHandler ¶
func (langs Languages) RedirectHandler() http.HandlerFunc
RedirectHandler returns an http handler which redirects to the localized version of r.URL according to the Accept-Language header. If r.URL it is already localized, the handler responds with a "not found" error in order to prevent a redirect loop. It is recommended to chain the handler behind your http router.
Directories ¶
Path | Synopsis |
---|---|
Command gotext-update-templates extracts and merges translations and generates a catalog.
|
Command gotext-update-templates extracts and merges translations and generates a catalog. |