包i18n不翻译

时间:2014-07-29 12:57:46

标签: go

我尝试在golang中编写我的第一个包。这个包只是goi18b的包装结构。请查看以下代码。

i18n.go

package i18n

import (
    "fmt"
    goi18n "github.com/nicksnyder/go-i18n/i18n"
)

var translateFunc goi18n.TranslateFunc

type I18n struct {
}

func NewI18n(filename string, language string) *I18n {
    goi18n.MustLoadTranslationFile(filename)
    translateFunc, _ = goi18n.Tfunc(language)
    return new(I18n)
}

func (i18n *I18n) ReadText(translationID string, args ...interface{}) string {
    fmt.Println(translateFunc("person_unread_email_count", 1, map[string]interface{}{
        "Person": "Bob",
    }))
    return translateFunc(translationID, args)
}

和测试文件i18n_test.go

package i18n

import "testing"
import "fmt"

var i18n *I18n = NewI18n("en-us.all.json", "en-US")

func TestComplexText(t *testing.T) {
    var str string
    str = i18n.ReadText("person_unread_email_count", 1, map[string]interface{}{
        "Person": "Bob",
    })
    fmt.Println(str)
}

作为输出我已经

Bob has 1 unread email.
person_unread_email_count
PASS

正如你所看到的,在i18n.go里面,文字就是翻译。

Bob has 1 unread email.

但是在i18n_test.go中,我期待相同的结果,但我已经

person_unread_email_count

我无法配置,我在这里做错了什么!

更新

当我将readtext函数更改为

func (i18n *I18n) ReadText(translationID string, args ...interface{}) string {
    fmt.Println(translateFunc(translationID, 1, map[string]interface{}{
        "Person": "Bob",
    }))
    fmt.Println(translateFunc(translationID, args))
    return translateFunc(translationID, args)
}

作为输出我已经

Bob has 1 unread email.
person_unread_email_count

我认为错误在参数args ... interface {}上。当我传递参数args

fmt.Println(translateFunc(translationID, args))

文字不去翻译。但是像这样,它就是翻译

fmt.Println(translateFunc(translationID, 1, map[string]interface{}{
    "Person": "Bob",
}))

为什么呢?

我忘记发布json文件

[
  {
    "id": "d_days",
    "translation": {
      "one": "{{.Count}} day",
      "other": "{{.Count}} days"
    }
  },
  {
    "id": "my_height_in_meters",
    "translation": {
      "one": "I am {{.Count}} meter tall.",
      "other": "I am {{.Count}} meters tall."
    }
  },
  {
    "id": "person_greeting",
    "translation": "Hello {{.Person}}"
  },
  {
    "id": "person_unread_email_count",
    "translation": {
      "one": "{{.Person}} has {{.Count}} unread email.",
      "other": "{{.Person}} has {{.Count}} unread emails."
    }
  },
  {
    "id": "person_unread_email_count_timeframe",
    "translation": {
      "one": "{{.Person}} has {{.Count}} unread email in the past {{.Timeframe}}.",
      "other": "{{.Person}} has {{.Count}} unread emails in the past {{.Timeframe}}."
    }
  },
  {
    "id": "program_greeting",
    "translation": "Hello world"
  },
  {
    "id": "your_unread_email_count",
    "translation": {
      "one": "You have {{.Count}} unread email.",
      "other": "You have {{.Count}} unread emails."
    }
  }
]

1 个答案:

答案 0 :(得分:0)

默认情况下,go test工具在成功时不会打印任何输出。您可以使用程序包log中的testing函数覆盖它,并在运行测试时设置-v标志。

有关详细信息,请参阅http://golang.org/cmd/go/#hdr-Description_of_testing_flags