forked from dromara/carbon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
language.go
executable file
·75 lines (67 loc) · 1.47 KB
/
language.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
package carbon
import (
"strconv"
"strings"
"github.com/golang-module/carbon/lang"
)
var (
defaultLocale = "en"
)
// Language 定义 Language 结构体
// define Language structure
type Language struct {
dir string
locale string
resources map[string]string
}
// NewLanguage return a new Language instance
// 初始化 Language 结构体
func NewLanguage() *Language {
return &Language{
locale: defaultLocale,
resources: make(map[string]string),
}
}
// SetLocale set language locale
// 设置区域
func (l *Language) SetLocale(locale string) error {
if len(l.resources) != 0 {
return nil
}
resources, err := lang.LoadLocale(locale)
if err != nil {
l.locale = locale
return err
}
l.locale = locale
l.resources = resources
return nil
}
// SetResources set language resources
// 设置资源
func (l *Language) SetResources(resources map[string]string) {
if len(l.resources) == 0 {
l.resources = resources
return
}
for k, v := range resources {
if _, ok := l.resources[k]; ok {
l.resources[k] = v
}
}
}
// translate translate by unit string
// 翻译转换
func (l *Language) translate(unit string, number int64) string {
if len(l.resources) == 0 {
l.SetLocale(defaultLocale)
}
slice := strings.Split(l.resources[unit], "|")
if len(slice) == 1 {
return strings.Replace(slice[0], "%d", strconv.FormatInt(number, 10), 1)
}
if number > 1 {
return strings.Replace(slice[1], "%d", strconv.FormatInt(number, 10), 1)
}
return slice[0]
}