在 Rust 中使用 Lefine
- 01
添加 HTTP 和 JSON crate
只需 reqwest 和 serde_json——没有需要安装的 Lefine crate。
Cargo.toml# First: npx lefine strings pull# It writes ./locales/en.json, ./locales/de.json, ... from your published strings.[dependencies]serde_json = "1"tokio = { version = "1", features = ["full"] } - 02
获取一个命名空间
CDN 为每个命名空间和语言提供一个 JSON 文件,并且总是返回 200。
src/i18n.rsuse std::collections::HashMap;/// `npx lefine strings pull` writes one JSON file per locale:/// ./locales/{locale}.json -> { "namespace": { "key": "text" } }pub fn load_messages( locale: &str,) -> std::io::Result<HashMap<String, serde_json::Value>> { let path = format!("locales/{locale}.json"); let raw = std::fs::read_to_string(path)?; Ok(serde_json::from_str(&raw)?)} - 03
在后台刷新
在进程内缓存该映射,并每 60 秒重新读取一次,与 CDN 的 max-age 一致。
src/main.rsuse std::time::Duration;// Keep the strings in process and re-read the files on an interval.// Run `npx lefine strings pull` on deploy (or on a schedule) to refresh them.tokio::spawn(async move { let mut ticker = tokio::time::interval(Duration::from_secs(60)); loop { ticker.tick().await; if let Ok(next) = load_messages("en") { *messages.write().await = next; } }});