Documentation
¶
Index ¶
- Constants
- Variables
- func CurrentLanguage() string
- func GetSupportedLanguages() []string
- func IsLanguageSupported(languageCode string) bool
- func SetLanguage(languageCode string) error
- func T(messageID string, templateData ...map[string]any) string
- func Te(messageID string, templateData ...map[string]any) (string, error)
- type Config
- type Translator
Constants ¶
const DefaultLanguage = "zh-CN"
DefaultLanguage is the default language for the i18n system.
Variables ¶
var ( // ErrUnsupportedLanguage is returned when an unsupported language code is provided. ErrUnsupportedLanguage = errors.New("unsupported language code") // ErrMessageIDEmpty is returned when a translation message ID is empty. ErrMessageIDEmpty = errors.New("messageID cannot be empty") )
Functions ¶
func CurrentLanguage ¶ added in v0.28.0
func CurrentLanguage() string
CurrentLanguage returns the language code the global translator is currently using.
func GetSupportedLanguages ¶
func GetSupportedLanguages() []string
GetSupportedLanguages returns a copy of all supported language codes.
func IsLanguageSupported ¶
IsLanguageSupported checks if the given language code is supported.
func SetLanguage ¶
SetLanguage changes the global translator to use the specified language. This is primarily intended for testing scenarios where you need to verify translations in different languages without restarting the process. If languageCode is empty, uses the environment variable or default language. The active locale set is preserved, so a translator built from a custom Config.Locales keeps those locales after switching language.
Types ¶
type Config ¶
type Config struct {
// Locales contains the embedded locale files (JSON format).
Locales embed.FS
}
Config defines the configuration for the i18n system.
type Translator ¶
type Translator interface {
// T translates a message ID to a localized string with graceful error handling.
// If translation fails, it returns the original messageID as a fallback.
T(messageID string, templateData ...map[string]any) string
// Te translates a message ID to a localized string and returns explicit error information.
// Use this when you need to distinguish between successful translation and failure.
Te(messageID string, templateData ...map[string]any) (string, error)
}
Translator defines the interface for message translation services.
func New ¶
func New(config Config) (Translator, error)
New creates a new translator instance with the provided configuration. The language is resolved from the environment variable or the default language.