コンテンツへスキップ
Rust

Rust の国際化

Lefine の crate はありません。Rust サービスは各 SDK と同じ CDN の JSON を読みます。reqwest と serde_json だけで十分で、新しい文言は再ビルドなしで届きます。

SDK
None needed
Source
Pulled JSON files
lefine · serde_json
01src/i18n.rs
use 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)?)}
02src/main.rs
use axum::{extract::State, routing::get, Json, Router};use std::{collections::HashMap, sync::Arc};use tokio::sync::RwLock;type Messages = Arc<RwLock<HashMap<String, serde_json::Value>>>;async fn greeting(State(messages): State<Messages>) -> Json<serde_json::Value> {    let messages = messages.read().await;    let hello = messages        .get("greeting")        .and_then(|ns| ns.get("hello"))        .and_then(|v| v.as_str())        .unwrap_or("Hello");    Json(serde_json::json!({ "message": hello }))}#[tokio::main]async fn main() {    let messages: Messages = Arc::new(RwLock::new(        load_messages("en").unwrap_or_default(),    ));    let app = Router::new()        .route("/greeting", get(greeting))        .with_state(messages);    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();    axum::serve(listener, app).await.unwrap();}
ns.get("hello")
Hello

CDN のメッセージを読む axum ハンドラー

メッセージは RwLock の背後に置かれ、タイマーで更新されます。

01/Setup

Rust から Lefine を使う

  1. 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"] }
  2. 02

    ネームスペースを取得

    CDN はネームスペースとロケールごとに JSON ファイルを返し、常に 200 を返します。

    src/i18n.rs
    use 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)?)}
  3. 03

    バックグラウンドで更新

    マップをプロセス内にキャッシュし、CDN の max-age に合わせて 60 秒ごとに再読み込みします。

    src/main.rs
    use 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;        }    }});
02/Capabilities

Rust サービスが得られるもの

  • SDK 不要 — Rust の crate も存在しないので、待つものはありません
  • HTTPS 経由のプレーンな JSONを serde_json でパース
  • axum、actix-web、Rocket、あるいは単純なバイナリでも動作
  • 新しい文言は約 60 秒で届き、再ビルドは不要
  • CDN で賄えない部分は REST API がカバー
  • ローカルカタログに rust-i18n を使っているなら、並行して使えます
Get started

無料で始める。

Rust サービスをローカライズする

プロジェクトを作成し、最初のロケールを公開して、Rust から HTTPS で読み取ります。