Dynamic setting language in Golang web framework Iris

203 Views Asked by At

I have these language files:

locales/
    en-US/
        a.yaml
        b.yaml
    zh-CN/
        a.yaml
        b.yaml
    DA/
        a.yaml
        b.yaml

set default language:

app.I18n.SetDefault("en-US")

How to set language dynamically according to l parameter:

www.sete.com/xx/xxx?l=en => set en-US
www.sete.com/xx/xxx?l=cn => set zh-CN
www.sete.com/xx/xxx?l=da => set DA

www.sete.com/xx/xxx?l=NotFound => default en-US

In addition, whenI set a language that doesn't exist:

www.sete.com/xx/xxx?l=NotFound 

I get an error in response like this:

{
    "user": "yaml%!(EXTRA string=Tom....)"
}

So , what should I do to better solve these problems? I tried my best, my English is not good, please help me.....

1

There are 1 best solutions below

0
kataras On

You can find Iris i18n examples at: https://github.com/kataras/iris/tree/master/_examples/i18n

If the language was not found, then the default language's key will be shown instead unless app.I18N.Strict is true. If the Strict field is false and the default language has no available key for the translation then the app.I18n.DefaultMessageFunc will be fired instead, you can take a look on how to configure what happens if a key does not exist at: https://github.com/kataras/iris/blob/7b6a8f1e26469ab3ae53cfe468d6e5202c75c2a8/_examples/i18n/basic/main.go#L38-L47