aboutsummaryrefslogtreecommitdiffhomepage
path: root/locale/translator.go
blob: 5560dd6ca834d05732f2470606d6ec8572458679 (plain)
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
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

package locale

import (
	"encoding/json"
	"fmt"
	"strings"
)

type Translator struct {
	Locales Locales
}

func (t *Translator) AddLanguage(language, translations string) error {
	var decodedTranslations Translation

	decoder := json.NewDecoder(strings.NewReader(translations))
	if err := decoder.Decode(&decodedTranslations); err != nil {
		return fmt.Errorf("Invalid JSON file: %v", err)
	}

	t.Locales[language] = decodedTranslations
	return nil
}

func (t *Translator) GetLanguage(language string) *Language {
	translations, found := t.Locales[language]
	if !found {
		return &Language{language: language}
	}

	return &Language{language: language, translations: translations}
}

func NewTranslator() *Translator {
	return &Translator{Locales: make(Locales)}
}