diff --git a/localization.go b/localization.go index db4a9fb..73d0fd5 100644 --- a/localization.go +++ b/localization.go @@ -3,6 +3,7 @@ package webutility import ( "encoding/json" "errors" + "fmt" "io/ioutil" "strings" "sync" @@ -21,36 +22,57 @@ func NewDictionary() *Dictionary { } } -func (d *Dictionary) AddLocale(loc, filePath string) error { - file, err := ioutil.ReadFile(filePath) +func (d *Dictionary) AddTranslations(directory string) error { + files, err := ioutil.ReadDir(directory) if err != nil { return err } - var data interface{} - err = json.Unmarshal(file, &data) - if err != nil { - return err - } + for _, fileInfo := range files { + fName := fileInfo.Name() + path := directory + fName + file, err := ioutil.ReadFile(path) + if err != nil { + return err + } - l := map[string]string{} - for k, v := range data.(map[string]interface{}) { - l[k] = v.(string) - } + fmt.Println(fName, path) + + break + + loc := stripFileExtension(fName) - mu.Lock() - defer mu.Unlock() - d.locales[loc] = l - d.supported = append(d.supported, loc) + var data interface{} + err = json.Unmarshal(file, &data) + if err != nil { + return err + } + + l := map[string]string{} + for k, v := range data.(map[string]interface{}) { + l[k] = v.(string) + } + + mu.Lock() + defer mu.Unlock() + d.locales[loc] = l + d.supported = append(d.supported, loc) + } return nil } +func (d *Dictionary) GetBestMatchLocale(acceptedLanguages string) (best string) { + accepted := d.parseAcceptedLanguageHeader(acceptedLanguages) + best = accepted[0] + return +} + func (d *Dictionary) Translate(loc, key string) string { return d.locales[loc][key] } -func (d *Dictionary) HasLocale(loc string) bool { +func (d *Dictionary) hasLocale(loc string) bool { for _, v := range d.supported { if v == loc { return true @@ -59,27 +81,21 @@ func (d *Dictionary) HasLocale(loc string) bool { return false } -func (d *Dictionary) SetDefaultLocale(loc string) error { - if !d.HasLocale(loc) { +func (d *Dictionary) setDefaultLocale(loc string) error { + if !d.hasLocale(loc) { return errors.New("dictionary does not contain translations for " + loc) } d.defaultLocale = loc return nil } -func (d *Dictionary) GetDefaultLocale() string { +func (d *Dictionary) getDefaultLocale() string { return d.defaultLocale } -func (d *Dictionary) GetBestMatchLocale(acceptedLanguages string) (best string) { - accepted := d.parseAcceptedLanguageHeader(acceptedLanguages) - best = accepted[0] - return -} - func (d *Dictionary) parseAcceptedLanguageHeader(acceptedLanguages string) (langs []string) { if acceptedLanguages == "" { - langs = append(langs, d.GetDefaultLocale()) + langs = append(langs, d.getDefaultLocale()) return } @@ -90,3 +106,7 @@ func (d *Dictionary) parseAcceptedLanguageHeader(acceptedLanguages string) (lang return } + +func stripFileExtension(full string) (stripped string) { + return +}