Blame view

localization.go 1.17 KB
9933169c8   Marko Tikvić   localization support
1
2
3
4
  package webutility
  
  import (
  	"encoding/json"
a205e8f40   Marko Tikvić   changes
5
  	"errors"
9933169c8   Marko Tikvić   localization support
6
7
  	"io/ioutil"
  )
f84e7607d   Marko Tikvić   added dictionary;...
8
  type Dictionary struct {
a205e8f40   Marko Tikvić   changes
9
10
11
  	locales       map[string]map[string]string
  	supported     []string
  	defaultLocale string
f84e7607d   Marko Tikvić   added dictionary;...
12
  }
ad8e9dd2a   Marko Tikvić   added middleware ...
13
14
  func NewDictionary() *Dictionary {
  	return &Dictionary{
f84e7607d   Marko Tikvić   added dictionary;...
15
16
17
  		locales: map[string]map[string]string{},
  	}
  }
9933169c8   Marko Tikvić   localization support
18

f84e7607d   Marko Tikvić   added dictionary;...
19
  func (d *Dictionary) AddLocale(loc, filePath string) error {
9933169c8   Marko Tikvić   localization support
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  	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)
  	}
f84e7607d   Marko Tikvić   added dictionary;...
35
  	d.locales[loc] = l
a205e8f40   Marko Tikvić   changes
36
  	d.supported = append(d.supported, loc)
9933169c8   Marko Tikvić   localization support
37
38
39
  
  	return nil
  }
f84e7607d   Marko Tikvić   added dictionary;...
40
41
42
  func (d *Dictionary) Translate(loc, key string) string {
  	return d.locales[loc][key]
  }
a205e8f40   Marko Tikvić   changes
43
44
45
  func (d *Dictionary) HasLocale(loc string) bool {
  	for _, v := range d.supported {
  		if v == loc {
f84e7607d   Marko Tikvić   added dictionary;...
46
47
48
49
  			return true
  		}
  	}
  	return false
9933169c8   Marko Tikvić   localization support
50
  }
a205e8f40   Marko Tikvić   changes
51
52
53
54
55
56
57
58
59
60
61
62
  
  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 {
  	return d.defaultLocale
  }