0x3d.Site
is designed for aggregating information.
check repository here
t
t: a translation util for go, inspired by GNU gettext
t: GNU gettext 的 Go 语言实现,Go 程序的国际化工具
Install 安装
go get -u github.com/youthlin/t
go.mod
require (
github.com/youthlin/t latest
)
Gitee 镜像:gitee.com/youthlin/gottext (gottext: go + gettext)
// 使用 gitee 镜像
// go.mod:
replace github.com/youthlin/t latest => gitee.com/youthlin/gottext latest
Usage 使用
path := "path/to/filename.po" // .po, .mo file
path = "path/to/po_mo/dir" // or dir.
// (mo po 同名的话,po 后加载,会覆盖 mo 文件,因为 po 是文本文件,方便修改生效)
// 1 bind domain 绑定翻译文件
t.Load(path) // 默认绑定在 default 域 会自动搜索路径下的文件,读取 po/mo 里的语言标签进行注册
t.Bind("my-domain", path) // 或者指定Ø文本域
// 2 set current domain 设置使用的文本域
t.SetDomain("my-domain")
// 3 set user language 设置用户语言
// t.SetLocale("zh_CN")
t.SetLocale(t.MostMatchLocale()) // empty to use system default
// 4 use the gettext api 使用 gettext 翻译接口
fmt.Println(t.T("Hello, world"))
fmt.Println(t.T("Hello, %v", "Tom"))
fmt.Println(t.N("One apple", "%d apples", 1)) // One apple
fmt.Println(t.N("One apple", "%d apples", 2)) // %d apples
// t.N(single, plural, n, args...)
// n => used to choose single or plural
// args => to format
// args... supported, used to format string
// 支持传入 args... 参数用于格式化输出
fmt.Println(t.N("One apple", "%d apples", 2, 2)) // 2 apples
fmt.Println(t.N("%[2]s has one apple", "%[2]s has %[1]d apples", 2, 200, "Bob"))
// Bob has 200 apples
t.X("msg_context_text", "msg_id")
t.X("msg_context_text", "msg_id")
t.XN("msg_context_text", "msg_id", "msg_plural", n)
API
T(msgID, args...)
N(msgID, msgIDPlural, n, args...) // and N64
X(msgCTxt, msgID, args...)
XN(msgCTxt, msgID, msgIDPlural, n, args...) // and XN64
D(domain)
L(locale)
// T: gettext
// N: ngettext
// X: pgettext
// XN: npgettext
// D: with domain
// L: with locale(language)
Domain 文本域
t.Bind(domain1, path1)
t.Bind(domain2, path2)
t.SetLocale("zh_CN")
t.T("msg_id") // use default domain
t.SetDomain(domain1)
t.T("msg_id") // use domain1
t.D(domain2).T("msg_id") // use domain2
t.D("unknown-domain").T("msg_id") // return "msg_id" directly
Language 指定语言
If you are building a web application, you may want each request use diffenrent language, the code below may help you:
如果你写的是 web 应用而不是 cli 工具,你可能想让每个 request 使用不同的语言,请看:
t.Load(path)
// a) Specify a language 可以指定语言
t.L("zh_CN").T("msg_id")
// b) every one use his own language 每个用户使用他接受的语言
// b.1) server supports 第一步,服务器支持的语言
langs := t.Locales()
// golang.org/x/text/language
// EN: https://blog.golang.org/matchlang
// 中文: https://learnku.com/docs/go-blog/matchlang/6525
var supported []language.Tag
for _, lang =range langs{
supported = append(supported, language.Make(lang))
}
matcher := language.NewMatcher(supported)
// b.2) user accept 第二步,用户接受的语言
// Judging by the browser header(Accept-Language)
// 根据浏览器标头获取用户语言
// or: userAccept := []language.Tag{ language.Make("lang-code-from-cookie") }
// 或从 cookie 中获取用户语言偏好
userAccept, q, err :=language.ParseAcceptLanguage("zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
// b.3) match 第三步,匹配出最合适的
matchedTag, index, confidence := matcher.Match(userAccept...)
// confidence may language.No, language.Low, language.High, language.Exact
// 这里 confidence 是指匹配度,可以根据你的实际需求决定是否使用匹配的语言。
// 如服务器支持 英文、简体中文,如果用户是繁体中文,那匹配度就不是 Exact,
// 这时根据实际需求决定是使用英文,还是简体中文。
userLang := langs[index]
t.L(userLang).T("msg_id")
// with domain, language 同时指定文本域、用户语言
t.D(domain).L(userLang).T("msg_id")
more examples can be find at: example_test.go
How to extract string 提取翻译文本
# if you use PoEdit, add a extractor
# 如果你使用 PoEdit,在设置-提取器中新增一个提取器
# Language: Go, *.go 语言填 Go 扩展名填 *.go 提取翻译的命令填写
# xgettext -C --add-comments=TRANSLATORS: --force-po -o %o %C %K %F
# 最后的三个输入框分别填写
# -k%k
# %f
# --from-code=%c
# keywords: 关键字这样设置:
# T:1;N:1,2;N64:1,2;X:2,1c;XN:2,3,1c;XN64:2,3,1c
xgettext -C --add-comments=TRANSLATORS: --force-po -kT -kN:1,2 -kX:2,1c -kXN:2,3,1c *.go
Done 已完成
- ✅ mo file 支持 mo 二进制文件
- ✅ extract from html templates 从模板文件中提取: xtemplate
go install github.com/youthlin/t/cmd/xtemplate@latest
Links 链接
- https://www.gnu.org/software/gettext/manual/html_node/index.html
- https://github.com/search?l=Go&q=gettext&type=Repositories
- https://github.com/antlr/antlr4/
- https://blog.gopheracademy.com/advent-2017/parsing-with-antlr4-and-go/
- https://xuanwo.io/2019/12/11/golang-i18n/ (中文)
License
Golang
Golang, or Go, is a statically typed programming language developed by Google. It’s known for its simplicity, performance, and support for concurrent programming. Go is widely used in cloud computing, server-side applications, and microservices.
GitHub - goyek/goyek: Task automation Go library
gommon/color at master · labstack/gommon
GitHub - blevesearch/bleve: A modern text/numeric/geo-spatial/vector indexing library for go
GitHub - schollz/progressbar: A really basic thread-safe progress bar for Golang applications
GitHub - free/concurrent-writer: Highly concurrent drop-in replacement for bufio.Writer
GitHub - mattn/go-colorable
GitHub - StudioSol/set: A simple Set data structure implementation in Go (Golang) using LinkedHashMap.
GitHub - essentialkaos/branca: Authenticated encrypted API tokens (IETF XChaCha20-Poly1305 AEAD) for Golang
Cloud Native Computing Foundation
GitHub - sakirsensoy/genv: Genv is a library for Go (golang) that makes it easy to read and use environment variables in your projects. It also allows environment variables to be loaded from the .env file.
GitHub - heetch/confita: Load configuration in cascade from multiple backends into a struct
GitHub - brianvoe/sjwt: Simple JWT Golang
GitHub - subpop/go-ini: Go package that encodes and decodes INI-files
GitHub - DylanMeeus/GoAudio: Go tools for audio processing & creation 🎶
GitHub - daviddengcn/go-colortext: Change the color of console text.
GitHub - andOTP/andOTP: [Unmaintained] Open source two-factor authentication for Android
GitHub - alfiankan/crab-config-files-templating: Dynamic configuration file templating tool for kubernetes manifest or general configuration files
GitHub - viney-shih/go-cache: A flexible multi-layer Go caching library to deal with in-memory and shared cache by adopting Cache-Aside pattern.
GitHub - TreyBastian/colourize: An ANSI colour terminal package for Go
GitHub - Evertras/bubble-table: A customizable, interactive table component for the Bubble Tea framework
GitHub - deatil/go-array: A Go package that read or set data from map, slice or json
GitHub - cometbft/cometbft: CometBFT (fork of Tendermint Core): A distributed, Byzantine fault-tolerant, deterministic state machine replication engine
GitHub - icza/session: Go session management for web servers (including support for Google App Engine - GAE).
GitHub - cristalhq/jwt: Safe, simple and fast JSON Web Tokens for Go
GitHub - lrita/cmap: a thread-safe concurrent map for go
GitHub - wzshiming/ctc: Console Text Colors - The non-invasive cross-platform terminal color library does not need to modify the Print method
GitHub - goradd/maps: map library using Go generics that offers a standard interface, go routine synchronization, and sorting
GitHub - alfiankan/teleterm: Telegram Bot Exec Terminal Command
GitHub - JeremyLoy/config: 12 factor configuration as a typesafe struct in as little as two function calls
GitHub - goraz/onion: Layer based configuration for golang
More on Golang
Programming Tips & Tricks
Code smarter, not harder—insider tips and tricks for developers.
Using Lua's Garbage Collector for Fine-Tuned Memory Management in Large Applications
#1
Leveraging Lua's Environment for Dynamic Code Execution and Security
#2
Mastering Lua's Table Manipulation: Advanced Techniques for Handling Large Data Sets
#3
Enhancing Code Readability and Debugging with Lua's Debug Library
#4
Leveraging Lua's Coroutines for Efficient Concurrency and Asynchronous Programming
#5
Leveraging Lua's Tail Call Optimization for Efficient Recursion and Avoiding Stack Overflow in Deep Recursive Functions
#6
Creating Custom Iterators in Lua for Traversing Complex Data Structures Like Graphs or Trees
#7
How to Maximize the Speed of Data Lookup in Lua Using Hash Tables and Optimized Table Management
#8
Advanced Techniques for Asynchronous Programming in Lua Using Coroutines for High-Performance Systems
#9
Mastering Efficient Memory Management in Lua with Weak Tables for Optimal Resource Utilization
#10
Error Solutions
Turn frustration into progress—fix errors faster than ever.
Visual Studio Crashes When Opening a File or Debugging a Project
#1
Visual Studio Cannot Connect to GitHub or Other Version Control System
#2
Visual Studio Freezes During Build or Debug Process
#3
Visual Studio Fails to Build Project with "Unable to Start Program" Error
#4
Visual Studio Shows "Cannot Open the Solution" Error Message When Opening a Project
#5
Visual Studio Crashes on Startup with "The application has encountered an error" Message
#6
Visual Studio Fails to Detect Changes in Files When Using Git Integration
#7
Visual Studio Crashes with "Unknown Exception" When Trying to Build Solution
#8
Visual Studio Hangs During Debugging with "Unable to Start Program" Error
#9
Visual Studio Fails to Load Solution with "The system cannot find the file specified" Error
#10
Shortcuts
The art of speed—shortcuts to supercharge your workflow.
Maximize Your Code Navigation with Cmd + Option + Left Arrow!
#1
Feel Like a Pro with Cmd + Control + D: Quickly View Definitions Like Never Before!
#2
Unlock Speed and Precision with Cmd + Shift + M: Maximize Your Productivity!
#3
Don’t Panic, Use Cmd + Option + I to Open the Developer Tools Now!
#4
Stop Wasting Time and Jump to Your File in an Instant with Cmd + Shift + O!
#5
Quickly Fix Your Code with ‘Cmd + Option + L’ for Instant Code Formatting!
#6
Transform Your Workflow with ‘Cmd + Shift + N’ to Open a New Window in No Time!
#7
Say Goodbye to Mouse: Master ‘Cmd + Shift + F’ to Search Your Entire Codebase!
#8
Struggling to Find Files? Hit ‘Cmd + P’ and Jump Right to Your File!
#9
Never Lose Your Progress Again: Use ‘Cmd + Z’ to Undo Mistakes Instantly!
#10
Made with ❤️
to provide resources in various ares.