duanfei1975 2017-08-25 18:34
浏览 88

Golang Web应用程序本地化

I have a web app written in golang, and I am planning to make it available in more than one language, I've taken a look at multiple available l18n packages but some things were not clear to me.

What packages would be ideal to determine the users locale and load the site accordingly? Like from browser preferences or location?

  • 写回答

1条回答 默认 最新

  • douqie6454 2017-08-25 20:06
    关注

    You can use https://github.com/nicksnyder/go-i18n/

    Then in your project you have to create a folder called i18n/ and use a function like this:

    import (
        "fmt"
        "io/ioutil"
    
        "github.com/nicksnyder/go-i18n/i18n"
    )
    
    func loadI18nFiles() {
        files, _ := ioutil.ReadDir("i18n")
        exists := false
    
        for _, file := range files {
            if err := i18n.LoadTranslationFile(fmt.Sprintf("i18n/%s", file.Name())); err != nil {
                log.Errorf("i18n: error loading file %s. err: %s", file.Name(), err)
            } else {
                log.Infof("i18n: lang file %s loaded", file.Name())
            }
    
            # Check if you have a default language
            if file.Name() == fmt.Sprintf("%s.json", "en-US") {
                exists = true
            }
        }
    
        if !exists {
            panic(fmt.Sprintf("Hey! You can't use a default language (%s) that doesn't exists on i18n folder", props.DefaultLang))
        }
    }
    

    Then to use, import the package and call the function:

    T, _ := i18n.Tfunc("es-AR", "en-US")
    
    fmt.Printf(T("key"))
    

    Each file inside i18n folder is a .json

    Example:

    en-US.json

    [
      {
        "id": "key",
        "translation": "Hello World"
      }
    ]
    

    es-AR.json

    [
      {
        "id": "key",
        "translation": "Hola Mundo"
      }
    ]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么