i18n

package
v1.24.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package i18n 提供 octo-server 的国际化 SDK 入口。bundle.go 负责 go-i18n 的 bundle 单例初始化、locale TOML 加载、以及把 codes 注册表的 DefaultMessage 注入为 source 语言消息。

Index

Constants

View Source
const (
	// EnvDefaultLanguage controls the runtime fallback language for requests
	// that carry no explicit language signal.
	EnvDefaultLanguage = "OCTO_DEFAULT_LANGUAGE"

	// EnvTrustedLangHeaderCIDRs controls which direct peer CIDRs may supply
	// X-Octo-Lang for service-to-service calls.
	EnvTrustedLangHeaderCIDRs = "OCTO_TRUSTED_LANG_HEADER_CIDRS"

	// EnvTrustedProxyCIDRs controls which direct peer CIDRs are trusted
	// reverse proxies for X-Forwarded-For peeling.
	EnvTrustedProxyCIDRs = "OCTO_TRUSTED_PROXY_CIDRS"

	// DefaultLanguage preserves the legacy deployment behavior for clients that
	// do not send Accept-Language yet.
	DefaultLanguage = "zh-CN"
)
View Source
const (
	// HeaderOctoLang 是受信网关/服务间调用使用的语言头。
	HeaderOctoLang = "X-Octo-Lang"
	// CookieLanguage 是前端与公开静态页共享的语言 cookie 名。
	CookieLanguage = "i18n_lang"
	// QueryLanguage 是 URL 显式语言选择参数。
	QueryLanguage = "lang"
)
View Source
const (
	// MetadataOctoLang is the gRPC metadata key used for language propagation.
	MetadataOctoLang = "x-octo-lang"
)
View Source
const SourceLanguage = "en-US"

SourceLanguage 是 source(D4)语言标签——AST extractor 输出 / 翻译模板基准。

Variables

View Source
var (
	// ErrSensitiveParamKey 表示 Params 中出现了不允许进入翻译模板的数据 key。
	ErrSensitiveParamKey = errors.New("i18n: sensitive param key")
)

Functions

func Bundle

func Bundle() (*i18n.Bundle, error)

Bundle 返回 lazy-init 的 go-i18n bundle 单例。

初始化顺序(关键):

  1. 创建 bundle,default language = SourceLanguage(en-US)。
  2. 从 codes.All() 注入 DefaultMessage 为 source 语言消息——保证即使 active.en-US.toml 为空,所有已注册 code 都能 fallback 到 DefaultMessage。
  3. 加载 locales/*.toml——同 ID 后加载者覆盖(即 TOML 可改写源消息, 翻译文件提供其他语言)。

初始化失败时 bundle 为 nil + bundleErr 非 nil;调用方(Localizer.Translate) 必须做 nil 检查并走 fallbackMessage 链路(D22)。Bundle 错误不 panic—— 服务启动后才被调用,panic 会让运行中进程崩溃,违背「fail-soft 翻译」原则。

func DefaultLanguageFromEnv

func DefaultLanguageFromEnv() (string, error)

DefaultLanguageFromEnv resolves OCTO_DEFAULT_LANGUAGE into a supported BCP-47 language tag. Empty env uses DefaultLanguage; invalid values are rejected so rollout misconfiguration fails during startup instead of surfacing per request.

func EarlyMiddleware

func EarlyMiddleware(opts MiddlewareOptions) gin.HandlerFunc

EarlyMiddleware negotiates language before auth and stores the decision in request context. The user-language override is applied lazily on the read side by LanguageFromContext (see ctx.go) so handlers and renderers see the merged decision without per-route post-auth middleware. The wrapped response writer keeps the Content-Language header consistent with that merged decision for successful responses (the ErrorRenderer path already re-evaluates at render time).

func InjectGRPCMetadata added in v1.6.0

func InjectGRPCMetadata(ctx context.Context) context.Context

InjectGRPCMetadata propagates the negotiated language into outgoing gRPC metadata.

func InjectHTTPHeaders

func InjectHTTPHeaders(req *http.Request)

InjectHTTPHeaders propagates the negotiated language to an outbound HTTP request.

func IsSensitiveParamKey

func IsSensitiveParamKey(key string) bool

IsSensitiveParamKey 返回 key 是否命中 D15/CI 约定的敏感字段正则。

func IsTrustedLangHeaderRequest

func IsTrustedLangHeaderRequest(r *http.Request, cidrs []*net.IPNet, trustedProxyCIDRs ...[]*net.IPNet) bool

IsTrustedLangHeaderRequest 判断请求调用方 IP 是否命中受信语言头 CIDR。

func LanguageOrDefault

func LanguageOrDefault(ctx context.Context, fallback string) string

LanguageOrDefault 返回 context 中的语言;不存在时返回 fallback。

func MatchSupportedLanguage

func MatchSupportedLanguage(raw string) (string, bool)

MatchSupportedLanguage 将输入语言规整到首期支持矩阵(en-US / zh-CN)。

func OutboundLanguage added in v1.6.0

func OutboundLanguage(ctx context.Context) string

OutboundLanguage 解析「发出方内容」(邮件等)应使用的语言。

与请求响应不同,邮件常在脱离请求 ctx 的路径上生成(异步 goroutine、未登录 的验证码发送),此时 ctx 里没有早期协商决策,也没有 UserInfo。本函数把 LanguageFromContext 的结果与 OCTO_DEFAULT_LANGUAGE 兜底合并:拿得到协商语言 就用它,否则退回部署默认语言。

这样调用点写法统一(一行拿 lang),且当未来把请求 ctx 或收件人语言接入这条 链路时无需改动发送层与模板层——结果会自动从 default 切换到真实语言。

func ParseCIDRList

func ParseCIDRList(value string) ([]*net.IPNet, error)

ParseCIDRList 解析逗号分隔 CIDR 列表,例如 "10.0.0.0/8,172.16.0.0/12"。

func ResolveDefaultLanguage

func ResolveDefaultLanguage(raw string) (string, error)

ResolveDefaultLanguage normalizes the configured default language.

func SupportedLanguages

func SupportedLanguages() []string

SupportedLanguages returns the current runtime language matrix.

func TrustedLangHeaderCIDRsFromEnv

func TrustedLangHeaderCIDRsFromEnv() ([]*net.IPNet, error)

TrustedLangHeaderCIDRsFromEnv parses OCTO_TRUSTED_LANG_HEADER_CIDRS.

func TrustedProxyCIDRsFromEnv

func TrustedProxyCIDRsFromEnv() ([]*net.IPNet, error)

TrustedProxyCIDRsFromEnv parses OCTO_TRUSTED_PROXY_CIDRS.

func UnaryClientLanguageInterceptor added in v1.6.0

func UnaryClientLanguageInterceptor() grpc.UnaryClientInterceptor

UnaryClientLanguageInterceptor propagates the negotiated language through gRPC metadata.

func UnaryServerLanguageInterceptor added in v1.6.0

func UnaryServerLanguageInterceptor() grpc.UnaryServerInterceptor

UnaryServerLanguageInterceptor reads propagated language metadata into context.

func ValidateRuntimeLocales

func ValidateRuntimeLocales(defaultLang string) error

ValidateRuntimeLocales checks the locale files required for startup: source language and configured default language must both have active TOML files in the embedded runtime bundle.

func WithLanguage

func WithLanguage(ctx context.Context, decision LanguageDecision) context.Context

WithLanguage 将语言协商结果写入 context.Context。

func WithLanguageIfHigherPriority

func WithLanguageIfHigherPriority(ctx context.Context, decision LanguageDecision) (context.Context, bool)

WithLanguageIfHigherPriority 仅当新来源优先级高于现有来源时覆盖 context。 这用于 D9 两段式中间件:Auth 后的 user.language 可以覆盖 Accept-Language/default, 但不能覆盖 trusted header、URL 或 cookie 这类显式选择。

Types

type Details

type Details map[string]any

Details 是客户端可见的错误上下文字段。渲染前必须按 codes.Code.SafeDetailKeys 过滤,避免 uid/token/raw_err 等内部信息泄漏。

func (Details) FilterBy

func (d Details) FilterBy(code codes.Code) Details

FilterBy 根据 Code.SafeDetailKeys 返回只包含白名单 key 的副本。 所有被丢弃的 key 都记录 i18n_unsafe_details_dropped_total{code,key}。

func (Details) FilterByKeys

func (d Details) FilterByKeys(codeID string, safeKeys []string) Details

FilterByKeys 根据 safeKeys 返回只包含白名单 key 的副本。

type ErrorRenderer

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

ErrorRenderer renders wkhttp.ErrorSpec through the octo-server i18n stack.

func NewErrorRenderer

func NewErrorRenderer(localizer Localizer) *ErrorRenderer

NewErrorRenderer creates a wkhttp.ErrorRenderer implementation.

func (*ErrorRenderer) Render

func (r *ErrorRenderer) Render(c *wkhttp.Context, spec wkhttp.ErrorSpec)

Render emits the compatibility envelope unconditionally:

  • error.{code,message,details,http_status} for new clients
  • msg/status for legacy clients

type LanguageDecision

type LanguageDecision struct {
	Language string
	Source   LanguageSource
}

LanguageDecision 记录一次语言协商结果及其来源。

func LanguageFromContext

func LanguageFromContext(ctx context.Context) (LanguageDecision, bool)

LanguageFromContext 读取 context 中的语言协商结果。

除了 EarlyMiddleware 在 ctx 中写入的早期协商决策(trusted header / query / cookie / Accept-Language / default),本函数还会顺带读取 wkhttp.UserFromCtx() 注入的 UserInfo.Language——它是 AuthMiddleware 经由 CacheTokenParser + UserLanguageResolver 解析出的"用户偏好真相源"。

D9 两段式协商:EarlyMiddleware 不能在 Auth 前知道 user.language,所以这里把 "用户偏好覆盖" 做成读侧延迟合并。只有当 user.language 非空且来源优先级 (LanguageSourceUser=30)严格高于 ctx 中现有决策时(典型场景:现有为 LanguageSourceAccept=20 或 LanguageSourceDefault=10),才让用户偏好生效。 trusted header / query / cookie 这类显式选择仍然胜出(D6 优先级顺序)。

func NegotiateLanguage

func NegotiateLanguage(r *http.Request, opts LanguageNegotiationOptions) LanguageDecision

NegotiateLanguage 按 D6 优先级协商请求语言: trusted X-Octo-Lang > URL lang > cookie i18n_lang > user.language > Accept-Language > default language。

X-Octo-Lang 默认根据 TCP RemoteAddr 命中 TrustedLangHeaderCIDRs 时采纳; 配置 TrustedProxyCIDRs 时,先对 X-Forwarded-For + RemoteAddr 从右向左 剥离可信反代,再用剥离后的调用方 IP 判定 TrustedLangHeaderCIDRs。

type LanguageNegotiationOptions

type LanguageNegotiationOptions struct {
	DefaultLanguage        string
	TrustedLangHeaderCIDRs []*net.IPNet
	TrustedProxyCIDRs      []*net.IPNet
	UserLanguage           string
}

LanguageNegotiationOptions 控制单次语言协商。

type LanguageSource

type LanguageSource string

LanguageSource 描述命中 D6 语言协商链的哪一级。

const (
	LanguageSourceTrustedHeader LanguageSource = "trusted_header"
	LanguageSourceGRPCMetadata  LanguageSource = "grpc_metadata"
	LanguageSourceQuery         LanguageSource = "query"
	LanguageSourceCookie        LanguageSource = "cookie"
	LanguageSourceUser          LanguageSource = "user"
	LanguageSourceAccept        LanguageSource = "accept_language"
	LanguageSourceDefault       LanguageSource = "default"
)

type Localizer

type Localizer interface {
	// Translate 将 code 解析为指定 lang 的本地化字符串。
	//
	// 入参:
	//   - code:   稳定 i18n key,必须在 codes.Register 已登记。
	//   - lang:   客户端协商出的 BCP-47 标签("zh-CN" / "en-US")。
	//             空字符串表示直接走 fallback chain。
	//   - params: 翻译模板插值数据(仅用于 message,不进入响应 details)。
	//
	// fallback chain(D22 六级,简化为四级实测有效路径):
	//   1. bundle: requested lang → fallback lang → source lang(go-i18n 自动)
	//   2. extreme fallback: codes.Code.DefaultMessages[lang]
	//   3. codes.Code.DefaultMessage(source 原文)
	//   4. code ID 本身(未注册 code,调用方应记 i18n_unknown_code_total)
	Translate(code, lang string, params Params) string
}

Localizer 是 SDK 对外的翻译入口。renderer / 业务门面 / 中间件均通过此接口 把 (code, lang, params) 解析为最终展示给客户端的 message。

func NewLocalizer

func NewLocalizer(fallbackLang string) Localizer

NewLocalizer 构造默认 Localizer。fallbackLang 通常对应 OCTO_DEFAULT_LANGUAGE (主方案 D5),空串则使用 DefaultLanguage。

Localizer 实例线程安全且无状态——所有数据从 Bundle 单例读取, 多 goroutine 可共享同一实例。

type MiddlewareOptions

type MiddlewareOptions struct {
	DefaultLanguage        string
	TrustedLangHeaderCIDRs []*net.IPNet
	TrustedProxyCIDRs      []*net.IPNet
}

MiddlewareOptions controls request language negotiation.

type Params

type Params map[string]any

Params 是翻译模板变量,只用于 message interpolation,不进入响应 details。 与 Details 使用不同命名类型,避免调用方把内部字段误放进客户端响应体。

func (Params) Render

func (p Params) Render(tmpl string) (string, error)

Render 用 Params 渲染一个 Go template 字符串。缺失 key 返回错误,由调用方 决定是否回退到未插值文案。

func (Params) TemplateData

func (p Params) TemplateData() (map[string]any, error)

TemplateData 校验 Params 并返回深一层 map 副本,供 go-i18n TemplateData 使用。 nil Params 返回 nil,便于无模板变量路径零分配传递。

type PropagationRoundTripper

type PropagationRoundTripper struct {
	Base http.RoundTripper
}

PropagationRoundTripper injects X-Octo-Lang into outbound HTTP requests.

func NewPropagationRoundTripper

func NewPropagationRoundTripper(base http.RoundTripper) *PropagationRoundTripper

NewPropagationRoundTripper wraps base with language propagation.

func (*PropagationRoundTripper) RoundTrip

func (t *PropagationRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

type SensitiveParamKeyError

type SensitiveParamKeyError struct {
	Key string
}

SensitiveParamKeyError 记录被拦截的 Params key。

func (SensitiveParamKeyError) Error

func (e SensitiveParamKeyError) Error() string

func (SensitiveParamKeyError) Unwrap

func (e SensitiveParamKeyError) Unwrap() error

type UserLanguageResolver

type UserLanguageResolver interface {
	Resolve(ctx context.Context, uid string) (string, error)
}

UserLanguageResolver returns the authoritative language preference for an authenticated user. Implementations are expected to consult a hot cache (e.g. Redis `user_language:{uid}`) first and fall back to the persistent store (`user.language` column) on cache miss, then write the result back to the cache.

Contract:

  • An empty return string means "no explicit preference"; callers must then fall back to the language already negotiated by EarlyMiddleware (Accept-Language / default).
  • A non-nil error means the lookup itself failed (cache + DB both unreachable). Callers should keep going with the snapshot value already carried by the token rather than 5xx-ing the request.
  • Implementations are responsible for input/output validation; if a stored value isn't a supported language tag, returning "" is the safe default.

The resolver is hooked into pkg/auth.CacheTokenParser so the resolved language ends up on wkhttp.UserInfo.Language, which LanguageFromContext then merges into the i18n language decision (LanguageSourceUser priority).

Directories

Path Synopsis
cmd
octo-i18n-extract command
Command octo-i18n-extract is the source-of-truth AST extractor for the i18n message marker pipeline (D18 in `i18n 最终方案.md` v7.1).
Command octo-i18n-extract is the source-of-truth AST extractor for the i18n message marker pipeline (D18 in `i18n 最终方案.md` v7.1).
Package codes 维护 i18n 错误码注册表。
Package codes 维护 i18n 错误码注册表。

Jump to

Keyboard shortcuts

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