language

package
v1.22.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2025 License: Apache-2.0 Imports: 16 Imported by: 25

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	LangVarName = `lang`
	DefaultLang = `zh-CN`
)
View Source
var (
	LangsGetter = func(c echo.Context, a *Language) (map[string]bool, string, error) {
		return a.List, a.Default, nil
	}
	TranslatorNew = func() Translator {
		return &Translate{_pool: true}
	}
)

Functions

func ParseHeader added in v1.6.0

func ParseHeader(al string, n int) []string

ParseHeader parses the Accept-Language header string into a slice of language tags. It removes any quality values (e.g. ";q=0.8") and splits the string by commas. The n parameter controls the maximum number of languages to return (similar to strings.SplitN). Returns an empty slice if the input string is empty.

Types

type Config

type Config struct {
	Project  string
	Default  string
	Fallback string
	AllList  []string

	// key: language, value: map[key]value.
	//
	// Example:
	// {
	// 	"en":{
	// 		"label":"English",
	// 		"flag":"🇺🇸"
	// 	},
	// 	"zh-CN":{
	// 		"label":"简体中文",
	// 		"flag":"🇨🇳"
	// 	},
	// }
	Extra map[string]param.Store

	RulesPath    []string
	MessagesPath []string

	// Reload indicates whether to reload the language file each time it is modified.
	Reload bool
	// contains filtered or unexported fields
}

func (Config) Clone added in v1.21.3

func (c Config) Clone() Config

func (Config) ExtraBy added in v1.22.9

func (c Config) ExtraBy(lang string) param.Store

ExtraBy returns the extra parameters for the specified language. If no extra parameters exist for the language or Extra is nil, returns an empty Store.

func (Config) FSFunc added in v1.3.0

func (c Config) FSFunc() func(string) http.FileSystem

FSFunc returns the configured http.FileSystem function.

func (*Config) Init added in v1.22.12

func (c *Config) Init()

Init initializes the language configuration by: - Normalizing default and fallback language codes - Normalizing all language codes in AllList - Creating a KVList with language codes as keys and formatted labels as values - Setting additional metadata (H) for each KV item from Extra data

func (Config) KVList added in v1.22.12

func (c Config) KVList() echo.KVList

func (*Config) SetFSFunc added in v1.3.0

func (c *Config) SetFSFunc(fsFunc func(string) http.FileSystem) *Config

type I18n

type I18n struct {
	*i18n.TranslatorFactory
	// contains filtered or unexported fields
}

func NewI18n

func NewI18n(c *Config) *I18n

NewI18n creates a new I18n instance with the given configuration. It initializes translator paths, creates a translator factory, and caches the default translator. If any errors occur during initialization, it will panic with the aggregated error messages. The first created instance will be set as the default instance if none exists.

func (*I18n) Close added in v1.22.13

func (a *I18n) Close()

Close stops the I18n monitor if it exists.

func (*I18n) Get

func (a *I18n) Get(langCode string) *i18n.Translator

Get returns the translator for the specified language code. If the translator is not cached, it will be loaded and cached using GetAndCache. The returned translator is safe for concurrent use.

func (*I18n) GetAndCache added in v1.6.0

func (a *I18n) GetAndCache(langCode string) *i18n.Translator

GetAndCache retrieves a translator for the specified language code and caches it. If the translator for the requested language cannot be loaded, it falls back to the default language. Returns the cached translator instance. Panics if errors occur while loading both the requested and default language translators.

func (*I18n) Monitor

func (a *I18n) Monitor() *I18n

Monitor starts watching language files for changes and automatically reloads them when modified. It uses a singleflight group to prevent concurrent reloads of the same file. The method watches for modify, delete and rename events on .yaml files in configured MessagesPath directories. Returns the I18n instance for method chaining.

func (*I18n) Reload

func (a *I18n) Reload(langCode string)

Reload reloads the translator for the specified language code. If the langCode ends with ".yaml", it will be trimmed and only the base name will be used. This method also removes the cached translator for the language.

func (*I18n) T

func (a *I18n) T(langCode, key string, args ...interface{}) (t string)

T translates the given key for the specified language code, optionally formatting the result with provided arguments. If args[0] is a map[string]string, it's used as translation variables. Otherwise, args are used for fmt.Sprintf formatting. Returns the translated string, formatted if arguments were provided.

func (*I18n) Translate

func (a *I18n) Translate(langCode, key string, args map[string]string) string

Translate translates the given key for the specified language code, using the provided args for variable substitution. If translation fails, returns the key with any group prefix removed. langCode: target language code key: translation key args: variables to substitute in the translation Returns: translated string or cleaned key if translation fails

type Language

type Language struct {
	List    map[string]bool // 语种列表
	Default string          // 默认语种
	I18n    *I18n           // I18n 实例
	// contains filtered or unexported fields
}

func New

func New(c ...*Config) *Language

New creates a new Language instance with optional configuration. If configuration is provided, it initializes the Language with the first config. The returned Language contains a sync.Pool for Translate instances and default settings.

func (*Language) AcquireTranslator added in v1.20.0

func (a *Language) AcquireTranslator(ctx echo.Context, langCode string, langs map[string]bool, langDefault string) Translator

AcquireTranslator gets a Translate instance from the pool and initializes it with the specified language code. The returned translator is ready to use for translation operations.

func (*Language) Close added in v1.22.13

func (a *Language) Close()

Close closes the I18n instance if it exists.

func (*Language) Config added in v1.18.0

func (a *Language) Config() *Config

Config returns the I18n configuration associated with the Language instance.

func (*Language) DetectHeader added in v1.1.0

func (a *Language) DetectHeader(r engine.Request, list map[string]bool) string

DetectHeader detects the preferred language from the Accept-Language header. It checks each language in the header against the provided list of valid languages, and returns the first valid match (including base language without region code). If no valid language is found, it returns the default language. Parameters:

  • r: the request containing the Accept-Language header
  • list: map of valid languages (keys are language codes, values are ignored)

Returns:

  • string: the detected language code or the default language

func (*Language) DetectURI

func (a *Language) DetectURI(c echo.Context, list map[string]bool) string

DetectURI detects the language code from the URI path. It checks if the detected language is valid according to the provided list. Returns the detected language code if valid, otherwise returns an empty string. The function also updates the dispatch path by removing the language prefix.

func (*Language) GetLangs added in v1.22.14

func (a *Language) GetLangs(c echo.Context) (map[string]bool, string, error)

GetLangs retrieves available languages and default language from context. Returns:

  • map of available languages (key: language code, value: enabled status)
  • default language code
  • error if any occurred during retrieval

If no languages are found, it creates a default map with the default language and 'en' as fallback.

func (*Language) Handler added in v1.6.0

func (a *Language) Handler(e echo.RouteRegister, i18nJSVarName string)

Handler registers HTTP routes for serving i18n messages in JSON and JavaScript formats. It provides two endpoints: - /i18n.json: returns messages as JSON - /i18n.js: returns messages as JavaScript with optional variable assignment i18nJSVarName specifies the JavaScript variable name to assign the messages to (optional)

func (*Language) Init

func (a *Language) Init(c *Config)

Init initializes the Language instance with the provided configuration. It sets up the language list based on the configuration, including the default language. If AllList is provided in the config, it registers all listed languages. Otherwise, it registers the default language and optionally English ('en') if not the default. It also initializes the I18n instance and starts monitoring for changes if Reload is enabled.

func (*Language) Middleware

func (a *Language) Middleware() echo.MiddlewareFunc

Middleware returns an echo middleware function that handles language detection and translation. It detects the language from query parameters, URI, cookies, or Accept-Language header in order. If a valid language is found, it sets the language cookie and attaches a translator to the context. The middleware will return an error if no valid languages are available or if language detection fails.

func (*Language) ReleaseTranslator added in v1.21.0

func (a *Language) ReleaseTranslator(tr Translator)

ReleaseTranslator releases the resources associated with the given translator. It calls the Release method on the provided Translate instance.

func (*Language) Set

func (a *Language) Set(lang string, on bool, args ...bool) *Language

Set 记录语言

  • on: 使用启用此语言
  • args[0]: setDefault 是否设置为默认语言
  • args[1]: normalized 是否已经标准格式化 lang 值

func (*Language) SetTranslatePool added in v1.22.14

func (a *Language) SetTranslatePool(pool *sync.Pool) *Language

func (*Language) SetTranslatePoolNew added in v1.22.14

func (a *Language) SetTranslatePoolNew(newFunc func() Translator) *Language

func (*Language) Valid

func (a *Language) Valid(lang string, langs map[string]bool) bool

Valid checks if the specified language is valid and enabled in the provided list. Returns true if the language is non-empty and marked as enabled in the list, false otherwise.

type Translate

type Translate struct {
	// contains filtered or unexported fields
}

func NewTranslate

func NewTranslate(ctx echo.Context, language string, langObject *Language, langs map[string]bool, langDefault string) *Translate

NewTranslate creates a new Translate instance and initializes it with the given language and language object. Returns a pointer to the initialized Translate struct.

func (*Translate) E added in v1.4.3

func (t *Translate) E(format string, args ...interface{}) error

E returns a new error with the translated message using the given format string and arguments.

func (*Translate) Lang

func (t *Translate) Lang() echo.LangCode

Lang returns the language code of the Translate instance

func (*Translate) LangDefault added in v1.18.0

func (t *Translate) LangDefault() string

LangDefault default language

func (*Translate) LangExists added in v1.18.0

func (t *Translate) LangExists(langCode string) bool

LangExists language code exists

func (*Translate) LangList added in v1.18.0

func (t *Translate) LangList() []string

LangList language list

func (*Translate) Release added in v1.19.2

func (t *Translate) Release()

Release releases the Translate instance resources and returns it to the pool if it was created from a pool. It sets both code and lang references to nil and optionally returns the instance to the translatePool.

func (*Translate) Reset added in v1.6.0

func (t *Translate) Reset(_ echo.Context, language string, langObject *Language, langs map[string]bool, langDefault string) Translator

Reset sets the language code and language object for the translator language: the language code to set langObject: the language object containing translations Returns the modified Translate instance for method chaining

func (*Translate) SetLang

func (t *Translate) SetLang(lang string)

SetLang sets the language code for translation using the specified language string.

func (*Translate) T

func (t *Translate) T(format string, args ...interface{}) string

T translates the given format string using the current language code and optional arguments. Returns the translated string.

type Translator added in v1.22.14

type Translator interface {
	Reset(ctx echo.Context, language string, langObject *Language, langs map[string]bool, langDefault string) Translator
	echo.Translator
	echo.Releaseable
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL