Rust에서 Lefine 사용하기
- 01
HTTP와 JSON 크레이트 추가
reqwest와 serde_json이면 됩니다 — 설치할 Lefine 크레이트는 없습니다.
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
백그라운드에서 갱신
맵을 프로세스 내에 캡시하고 CDN의 max-age에 맞춰 60초마다 다시 읽으세요.
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; } }});