简体   繁体   中英

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. eg 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.

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],
    })
}

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM