-
Notifications
You must be signed in to change notification settings - Fork 0
/
gotext_json_loader.go
86 lines (69 loc) · 1.94 KB
/
gotext_json_loader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package loader
import (
"encoding/json"
"errors"
"io"
"io/ioutil"
"time"
"github.com/rs/zerolog/log"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
type langmessage struct {
ID string `json:"id"`
Message string `json:"message"`
Translation string `json:"translation"`
}
type langmessages struct {
Language string `json:"language"`
Messages []langmessage `json:"messages"`
}
// GoTextJSONLoader loads strings from files in the JSON format supported by gotext.
type GoTextJSONLoader struct {
catalogsByTagStr map[string]*StringCatalog
}
// NewGoTextJSONLoader factory method.
func NewGoTextJSONLoader() *GoTextJSONLoader {
return &GoTextJSONLoader{
catalogsByTagStr: map[string]*StringCatalog{},
}
}
// StringsByTag gets the string table for the given language tag.
func (ldr *GoTextJSONLoader) StringsByTag(tag language.Tag) (*StringCatalog, error) {
if cat, ok := ldr.catalogsByTagStr[tag.String()]; ok {
return cat, nil
}
return nil, errors.New("catalog not found for tag " + tag.String())
}
// NeedsTag implements the Loader interface.
func (ldr *GoTextJSONLoader) NeedsTag() bool {
// Not needed because the langauge is embedded in the file.
return false
}
// ReadMessages implements the Loader interface.
func (ldr *GoTextJSONLoader) ReadMessages(reader io.Reader, tag *language.Tag, modTime time.Time) error {
data, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
lm := langmessages{}
err = json.Unmarshal([]byte(data), &lm)
if err != nil {
return err
}
t, err := language.Parse(lm.Language)
if err != nil {
return err
}
tagStr := t.String()
ldr.catalogsByTagStr[tagStr] = NewStringCatalog(modTime)
for _, m := range lm.Messages {
log.Debug().Str("languagetag", tagStr).
Str("id", m.ID).
Str("translation", m.Translation).
Msg("Loading string")
message.SetString(t, m.ID, m.Translation)
ldr.catalogsByTagStr[tagStr].Strings[m.ID] = m.Translation
}
return nil
}