2017-11-20 06:10:04 +01:00
|
|
|
// 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"
|
|
|
|
)
|
|
|
|
|
2017-11-26 00:56:44 +01:00
|
|
|
// Translator manage supported locales.
|
2017-11-20 06:10:04 +01:00
|
|
|
type Translator struct {
|
2017-11-26 00:56:44 +01:00
|
|
|
locales Locales
|
2017-11-20 06:10:04 +01:00
|
|
|
}
|
|
|
|
|
2017-11-26 00:56:44 +01:00
|
|
|
// AddLanguage loads a new language into the system.
|
2017-11-20 06:10:04 +01:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2017-11-26 00:56:44 +01:00
|
|
|
t.locales[language] = decodedTranslations
|
2017-11-20 06:10:04 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-11-26 00:56:44 +01:00
|
|
|
// GetLanguage returns the given language handler.
|
2017-11-20 06:10:04 +01:00
|
|
|
func (t *Translator) GetLanguage(language string) *Language {
|
2017-11-26 00:56:44 +01:00
|
|
|
translations, found := t.locales[language]
|
2017-11-20 06:10:04 +01:00
|
|
|
if !found {
|
|
|
|
return &Language{language: language}
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Language{language: language, translations: translations}
|
|
|
|
}
|
|
|
|
|
2017-11-26 00:56:44 +01:00
|
|
|
// NewTranslator creates a new Translator.
|
2017-11-20 06:10:04 +01:00
|
|
|
func NewTranslator() *Translator {
|
2017-11-26 00:56:44 +01:00
|
|
|
return &Translator{locales: make(Locales)}
|
2017-11-20 06:10:04 +01:00
|
|
|
}
|