i18n

package
v1.8.7 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

README

antgo/i18n - Internationalization (i18n) Library / 国际化(i18n)库

中文 | English


中文

📖 简介

antgo/i18n 是一款基于Go语言的高效国际化(i18n)库,旨在为应用程序提供多语言支持。支持从文件加载语言包,缓存翻译结果,自动处理多语言切换,且具有高性能和低内存消耗。
适用于需要处理多语言支持、日期时间格式化、复数规则等场景。

GitHub地址: github.com/small-ek/antgo/i18n

📦 安装
go get github.com/small-ek/antgo/i18n
🚀 快速开始
初始化国际化模块
package main

import (
	"fmt"
	"github.com/small-ek/antgo/i18n"
)

func main() {
	// 配置国际化设置
	config := i18n.Config{
		DefaultLang:    "en",      // 默认语言 | Default language
		FallbackLang:   "zh-CN",   // 备用语言 | Fallback language
		TranslationsDir: "./translations", // 翻译文件目录 | Translation files directory
		SupportedLangs: []string{"en", "zh-CN", "es", "fr"}, // 支持的语言 | Supported languages
		CacheEnabled:   true,      // 启用翻译缓存 | Enable translation cache
		MaxCacheSize:   100,      // 缓存最大条目数 | Maximum cache entries
	}

	// 初始化国际化模块
	if err := i18n.New(config); err != nil {
		fmt.Println("初始化错误:", err)
		return
	}

	// 使用翻译功能
	fmt.Println(i18n.T(nil, "hello_world")) // 输出: Hello, World!
}
使用翻译功能
package main

import (
	"fmt"
	"github.com/small-ek/antgo/i18n"
)

func main() {
	// 假设已初始化国际化模块

	// 获取翻译文本
	fmt.Println(i18n.T(nil, "hello_world")) // 输出: Hello, World!
	
	// 获取复数形式翻译
	fmt.Println(i18n.TPlural(nil, 2, "item_count", 2)) // 输出: 2 items

	// 获取本地化日期时间格式
	fmt.Println(i18n.TDate(nil, time.Now())) // 输出: 2025-02-08T12:00:00Z(根据语言设置可能不同)
}
✨ 核心特性
特性 描述
支持多语言 通过加载不同语言的翻译包支持多语言
高效缓存 启用翻译缓存,减少重复翻译请求
日期时间本地化 根据语言设置提供本地化日期和时间格式
复数规则支持 自动处理单数和复数翻译
严格的错误处理 提供详细的错误信息,避免崩溃
⚠️ 注意事项
  1. 配置中的翻译文件目录必须包含有效的翻译文件(支持JSON, TOML, YAML格式)。
  2. 确保输入的语言代码在支持的语言列表中有效。
  3. 默认语言和备用语言必须存在于加载的语言包中。
🤝 参与贡献

贡献指南 | 提交Issue


English

📖 Introduction

antgo/i18n is an efficient internationalization (i18n) library for Go, designed to provide multi-language support for applications. It supports loading language bundles from files, caching translation results, and automatically handling language switching with high performance and low memory consumption.
Ideal for scenarios that require multi-language support, date/time formatting, pluralization rules, etc.

GitHub URL: github.com/small-ek/antgo/i18n

📦 Installation
go get github.com/small-ek/antgo/i18n
🚀 Quick Start
Initializing the Internationalization Module
package main

import (
	"fmt"
	"github.com/small-ek/antgo/i18n"
)

func main() {
	// Configuration for internationalization
	config := i18n.Config{
		DefaultLang:    "en",      // Default language
		FallbackLang:   "zh-CN",   // Fallback language
		TranslationsDir: "./translations", // Translation files directory
		SupportedLangs: []string{"en", "zh-CN", "es", "fr"}, // Supported languages
		CacheEnabled:   true,      // Enable translation cache
		MaxCacheSize:   100,      // Maximum cache size
	}

	// Initialize the internationalization module
	if err := i18n.New(config); err != nil {
		fmt.Println("Initialization error:", err)
		return
	}

	// Using translation feature
	fmt.Println(i18n.T(nil, "hello_world")) // Output: Hello, World!
}
Using the Translation Features
package main

import (
	"fmt"
	"github.com/small-ek/antgo/i18n"
)

func main() {
	// Assume the internationalization module has been initialized

	// Get translated text
	fmt.Println(i18n.T(nil, "hello_world")) // Output: Hello, World!
	
	// Get pluralized translation
	fmt.Println(i18n.TPlural(nil, 2, "item_count", 2)) // Output: 2 items

	// Get localized date and time format
	fmt.Println(i18n.TDate(nil, time.Now())) // Output: 2025-02-08T12:00:00Z (depending on language setting)
}
✨ Key Features
Feature Description
Multi-language Support Supports multiple languages by loading different language bundles
Efficient Caching Enables translation caching to reduce repeated translation requests
Localized Date/Time Provides localized date and time formats based on language settings
Pluralization Support Automatically handles singular and plural translations
Safe Error Handling Provides detailed error messages to avoid crashes
⚠️ Important Notes
  1. The translation files directory specified in the configuration must contain valid translation files (supports JSON, TOML, YAML formats).
  2. Ensure that the input language code is valid in the list of supported languages.
  3. The default and fallback languages must exist within the loaded language bundles.
🤝 Contributing

Contribution Guide | Open an Issue

⬆ Back to Top

Documentation

Index

Constants

View Source
const (
	DefaultLanguageCode   = "zh-CN"      // 默认语言代码 | Default language code
	ContextKeyLanguage    = "i18nBundle" // 上下文存储键名 | Context storage key name
	MaxCacheEntries       = 1000         // 最大缓存条目数 | Maximum cache entries
	DefaultDateTimeLayout = time.RFC3339 // 默认日期时间格式 | Default datetime format
)

默认配置参数

Variables

This section is empty.

Functions

func Middleware added in v1.8.7

func Middleware() gin.HandlerFunc

Middleware 语言包注入中间件 Language bundle injection middleware

func New added in v1.3.0

func New(config Config) error

Init 初始化国际化模块 Initialize internationalization module

参数:

config - 配置参数结构体 | Configuration parameters struct

返回:

error - 初始化过程中遇到的错误 | Error during initialization

func T added in v1.8.7

func T(c *gin.Context, key string, args ...interface{}) string

func TDate added in v1.8.7

func TDate(c *gin.Context, t time.Time) string

TDate 本地化日期时间格式化 Localized datetime formatting

func TPlural added in v1.8.7

func TPlural(c *gin.Context, count int, key string, args ...interface{}) string

TPlural 获取复数形式翻译 Get plural-form translation

Types

type Config added in v1.8.7

type Config struct {
	DefaultLang      string            `comment:"默认语言代码(如'en')| Default language code"`
	FallbackLang     string            `comment:"备用回退语言代码 | Fallback language code"`
	TranslationsDir  string            `comment:"翻译文件目录路径 | Translation files directory path"`
	SupportedLangs   []string          `comment:"支持的语言列表 | Supported languages list"`
	CacheEnabled     bool              `comment:"是否启用翻译缓存 | Enable translation cache"`
	MaxCacheSize     int               `comment:"缓存最大容量 | Maximum cache size"`
	CustomPluralRule PluralRuleHandler `comment:"自定义复数规则处理器 | Custom plural rule handler"`
	DateTimeLayouts  map[string]string `comment:"各语言日期时间格式 | Per-language datetime formats"`
}

Config 国际化配置结构 Internationalization configuration structure

type LanguageBundle added in v1.8.7

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

LanguageBundle 语言包数据结构 Language bundle data structure

type PluralRuleHandler added in v1.8.7

type PluralRuleHandler func(lang string, n int, key string, args ...interface{}) string

PluralRuleHandler 复数规则处理函数类型 Plural rule handler function type

Jump to

Keyboard shortcuts

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