diff --git a/localization.go b/localization.go index 7386f0e..aa4bdb1 100644 --- a/localization.go +++ b/localization.go @@ -2,6 +2,7 @@ package webutility import ( "encoding/json" + "fmt" "io/ioutil" "net/http" "path" @@ -17,12 +18,10 @@ type Dictionary struct { defaultLocale string } -func NewDictionary(def string) *Dictionary { - d := Dictionary{ +func NewDictionary() *Dictionary { + return &Dictionary{ locales: map[string]map[string]string{}, } - d.defaultLocale = def - return &d } func (d *Dictionary) AddTranslations(directory string) error { @@ -58,10 +57,8 @@ func (d *Dictionary) AddTranslations(directory string) error { d.supported = append(d.supported, loc) } - if d.defaultLocale == "" { - if len(d.supported) > 0 { - d.defaultLocale = d.supported[0] - } + if d.defaultLocale == "" && len(d.supported) > 0 { + d.defaultLocale = d.supported[0] } return nil @@ -88,7 +85,17 @@ func (d *Dictionary) Translate(loc, key string) string { return d.locales[loc][key] } -func (d *Dictionary) hasLocale(loc string) bool { +func (d *Dictionary) SetDefaultLocale(loc string) error { + if !d.contains(loc) { + return fmt.Errorf("locale file not loaded: %s", loc) + } + + d.defaultLocale = loc + + return nil +} + +func (d *Dictionary) contains(loc string) bool { for _, v := range d.supported { if v == loc { return true