nicksnyder / go-i18n

Translate your Go program into multiple languages.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Any example present how to use message format in JSON

KingWu opened this issue · comments

commented

Hi, i feel confuse on how to use message format in Json. Any demo example?

key point:

bundle.RegisterUnmarshalFunc("json", json.Unmarshal)

example code

https://github.com/CarsonSlovoka/go-i18n/blob/d81b3367d02fa33d2d37f37ea05050b335098107/v2/example/basic.go#L220-L235

👆 where simpleTest

Other: custom format

default is support TOML, YAML, JSON

If the above format is not satisfied for you, you can define your Unmarshal Function

// UnmarshalFunc unmarshals data into v.
type UnmarshalFunc func(data []byte, v interface{}) error

normally v should be something like this:

map[string]interface{}

I mean, suppose your contents is below

[IDHi]
other="Hi"

if err = unmarshalFunc(buf, &raw); err != nil {

  • buf: file contents ([]byte)
  • raw: you must let your unmarshalFunc create an item like that {interface{} | map[string]interface{}{"IDHi": Hi}

There is a TOML example here and you can just convert that file to an equivalent JSON file using a converter like https://pseitz.github.io/toml-to-json-online-converter/ to get the equivalent JSON file:

{
  "HelloPerson": "Hello {{.Name}}",
  "MyUnreadEmails": {
    "description": "The number of unread emails I have",
    "one": "I have {{.PluralCount}} unread email.",
    "other": "I have {{.PluralCount}} unread emails."
  },
  "PersonUnreadEmails": {
    "description": "The number of unread emails a person has",
    "one": "{{.Name}} has {{.UnreadEmailCount}} unread email.",
    "other": "{{.Name}} has {{.UnreadEmailCount}} unread emails."
  }
}

There are also a JSON example in this test:

go-i18n/i18n/bundle_test.go

Lines 101 to 118 in 7c6508d

func TestJSON(t *testing.T) {
bundle := NewBundle(language.English)
bundle.MustParseMessageFileBytes([]byte(`{
"simple": "simple translation",
"detail": {
"description": "detail description",
"other": "detail translation"
},
"everything": {
"description": "everything description",
"zero": "zero translation",
"one": "one translation",
"two": "two translation",
"few": "few translation",
"many": "many translation",
"other": "other translation"
}
}`), "en-US.json")