|
|
@@ -1,2 +1,75 @@
|
|
|
-# i18n
|
|
|
+# i18n - translations module for Go
|
|
|
|
|
|
+i18n is a set of functions to help with project translations and language detection.
|
|
|
+
|
|
|
+## Usage
|
|
|
+
|
|
|
+First get the module:
|
|
|
+
|
|
|
+ go get go.deck17.com/i18n
|
|
|
+
|
|
|
+
|
|
|
+Import the the module in the final project:
|
|
|
+
|
|
|
+ import (
|
|
|
+ "go.deck17.com/i18n"
|
|
|
+ "go.deck17.com/i18n/detect"
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+## Translate text
|
|
|
+
|
|
|
+i18n exports a single constructor that accepts a map[string]map[string]string with language and translations maps. As
|
|
|
+a result it returns two funcs, each accepting language code as a string, key to translate and optional arguments for
|
|
|
+string substitution (as formatted by fmt.Sprintf). The returned functions are defined as:
|
|
|
+
|
|
|
+ func(string, string, args ...any) string
|
|
|
+ func(string, string, args ...any) error
|
|
|
+
|
|
|
+### Initialize translator
|
|
|
+
|
|
|
+This is an example how to initialize the translator:
|
|
|
+
|
|
|
+ var translations = map[string]map[string]string{
|
|
|
+ "en": {
|
|
|
+ "hello": "Hello World!",
|
|
|
+ },
|
|
|
+ "de": {
|
|
|
+ "hello": "Hallo, Welt!",
|
|
|
+ },
|
|
|
+ }
|
|
|
+
|
|
|
+ // in this case "en" is the default language
|
|
|
+ var T, Terr = i18n.NewTranslator(translations, "en")
|
|
|
+
|
|
|
+
|
|
|
+### Use translator in the code
|
|
|
+
|
|
|
+Translate text inside Go code:
|
|
|
+
|
|
|
+ fmt.Printf("Translated text (en): %s\n", T("en", "hello"))
|
|
|
+ fmt.Printf("Translated text (de): %s\n", T("de", "hello"))
|
|
|
+
|
|
|
+### Translated error messages
|
|
|
+
|
|
|
+Similarly, Terr can be used to generate localized error messages instead of strings:
|
|
|
+
|
|
|
+ func do_stuff() error {
|
|
|
+ return Terr("en", "hello")
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+## Detecting language in http server applications
|
|
|
+
|
|
|
+The i18n/detect module contains a function that can be used to detect currently selected web language. It uses query
|
|
|
+string and cookies to do so and automatically sends / updates cookie when language is changed (with query parameter).
|
|
|
+
|
|
|
+ // the first language in the list is used as a default language
|
|
|
+ var detectLanguage = detect.NewHttpDetector(
|
|
|
+ []string{"en", "de"}, // list of languages
|
|
|
+ "/", // cookie path
|
|
|
+ 31536000, // max age in seconds
|
|
|
+ }
|
|
|
+
|
|
|
+The result function detectLanguage accepts http.ResponseWriter and \*http.Request arguments and returns string with
|
|
|
+language code.
|