Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the standard/ idiomatic way to handle multilingual Go web apps?

I'm working on a website which needs to deliver web pages in different languages as selected by the user. e.g. if the user selects Spanish as his preferred language, the server should send text elements of web pages in Spanish.

What is the standard way of doing it in Go? I'd also love to know what methods you guys are using.

Thanks.

like image 626
Kshitij Kumar Avatar asked Jul 03 '18 04:07

Kshitij Kumar


People also ask

How is multilingual implemented in Outsystems?

Add Other Languages To add a language Locale, do the following: Right-click the Multilingual Locales folder in the elements tree of the Data Tab and select Add Locale... option.


Video Answer


2 Answers

I allways use a map and define a function on it, which returns the text for a given key:

type Texts map[string]string

func (t *Texts) Get(key string) string{
    return (*t)[key]
}

var texts = map[string]Texts{
    "de":Texts{
        "title":"Deutscher Titel",
    },
    "en":Texts{
        "title":"English title",
    },
}

func executeTemplate(lang string){
    tmpl, _ := template.New("example").Parse(`Title: {{.Texts.Get "title" }} `)
    tmpl.Execute(os.Stdout,struct{
        Texts Texts
    }{
        Texts: texts[lang],
    })
}
like image 197
KeKsBoTer Avatar answered Sep 21 '22 13:09

KeKsBoTer


If a user's preferred language has a possibility of being unavailable, you can use Golang's text/language package to match requested languages to supported languages.

This type of language matching is a non-trivial problem as outlined in this excellent post in The Go Blog.

To use the language package, create a matcher with a slice of supported languages:

var serverLangs = []language.Tag{
    language.AmericanEnglish, // en-US fallback
    language.German,          // de
}

var matcher = language.NewMatcher(serverLangs)

Then match against one or more preferred languages. (The preferred language may be based on the user's IP address or the Accept-Language header.)

var userPrefs = []language.Tag{
    language.Make("gsw"), // Swiss German
    language.Make("fr"),  // French
}

tag, index, confidence := matcher.Match(sortLanguageTags(&langs, DescendingQuality)...)

To retrieve the corresponding text for the language, you can use the tag.String() method:

type Translation map[string]string
type Translations map[string]Translation

translations := Translations{
        "knee": {
            language.German.String():          "knie",
            language.AmericanEnglish.String(): "knee",
        },
    }

fmt.Println(translations["knee"][tag.String()]) // prints "knie"
like image 29
Feckmore Avatar answered Sep 17 '22 13:09

Feckmore