-
Notifications
You must be signed in to change notification settings - Fork 1
/
i18n.go
68 lines (53 loc) · 1.36 KB
/
i18n.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
package i18n
import (
"fmt"
"errors"
)
type LocaleMissing struct{
Code string
}
func (m LocaleMissing) Error() string {
return fmt.Sprintf("Missing `%s` locale", m.Code)
}
var (
locales map[string]*Locale
currentLocale *Locale
)
func init() {
resetLocales()
}
func resetLocales() {
locales = make(map[string]*Locale)
}
// Adds a locale to the available locales.
func AddLocale(locale *Locale) {
locales[locale.Code] = locale
}
// Return the locale with the specified code
func GetLocale(code string) *Locale {
return locales[code]
}
// Sets the current locale. Returns a LocaleMissing error if no locale has been added with the specified code.
func SetLocale(code string) error {
currentLocale = GetLocale(code)
if currentLocale == nil {
return &LocaleMissing{ code }
}
return nil
}
// Returns the current locale.
func CurrentLocale() *Locale {
return currentLocale
}
// Calls Translate on the current locale.
// An error is returned if the current locale is not set or if the translation is missing in the current locale.
func Translate(key string, args ...interface{}) (string, error) {
if currentLocale != nil {
return currentLocale.Translate(key, args...)
}
return "", errors.New("Current locale is not set")
}
// Alias for Translate.
func T(key string, args ...interface{}) (string, error) {
return Translate(key, args...)
}