Search code examples
gowebmultilingual

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.


Solution

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