locale_utility.go 821 Bytes
package webutility

import (
	"encoding/json"
	"io/ioutil"
)

type Dictionary struct {
	locales map[string]map[string]string
}

func NewDictionary() Dictionary {
	return Dictionary{
		locales: map[string]map[string]string{},
	}
}

func (d *Dictionary) AddLocale(loc, filePath string) error {
	file, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}

	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)
	}
	d.locales[loc] = l

	return nil
}

func (d *Dictionary) Translate(loc, key string) string {
	return d.locales[loc][key]
}

func (d *Dictionary) SupportsLocale(loc string) bool {
	for k, _ := range d.locales {
		if k == loc {
			return true
		}
	}
	return false
}