Lingara Lingara 說明文件 學習指南 API 程式庫 App 建立 網頁版
語言: 粵語

Rust

呢頁係由英文翻譯過嚟嘅。如果兩個版本有出入,以英文頁為準。 睇英文頁

Rust 函式庫係 crates.io 上面嘅 lingara crate。佢要 Rust 1.87 或者更新嘅版本,喺 Tokio 執行環境上面行。TLS 預設由 rustls 提供,亦可以透過一個 feature 改用平台自己嘅 TLS。

用起嚟點樣

  • 每個呼叫都係一個 async fn,回傳 Result。想取消呼叫,就掉咗佢嘅 future;想取消串流,就掉咗個串流。
  • 回應標頭一到,串流就跟住到,形式係一個由結果組成嘅 Stream。用 .next().await 讀佢。
  • 錯誤係一個有四個變體嘅 Error 列舉。如果 API 講咗要等幾耐,Error::retry_after 就會回傳嗰個時間。
  • 用 Client::builder() 砌一個用戶端。想共用連線池,可以畀你自己嘅 reqwest::Client 佢,但係唔好幫嗰個用戶端設總逾時,否則佢會將長嘅串流斬短。想幫單一個呼叫設截止時間,就用 tokio::time::timeout 包住佢。

下面嘅範例會安裝 crate、建立用戶端、用串流攞一份詞彙清單,同埋處理錯誤。

Rust

cargo add lingara@0.1.0-alpha.6
cargo add tokio --features macros,rt-multi-thread

Rust

use lingara::Client;

let client = Client::builder()
    .client_credentials(std::env::var("LINGARA_CLIENT_ID")?, std::env::var("LINGARA_CLIENT_SECRET")?)
    .build()?;

Rust

use lingara::models::{GenerateVocabularyEvent, VocabRequest};
use std::num::NonZeroU8;

let request = VocabRequest { level: 2, source_lang: "en".into(), target_lang: "zh".into(), count: NonZeroU8::new(8) };
let mut stream = client.generate_vocabulary(&request).await?;
while let Some(event) = stream.next().await {
    if let GenerateVocabularyEvent::Item(item) = event? {
        println!("{} {}", item.word, item.translation);
    }
}

Rust

use lingara::Error;

let result = client.get_usage().await;
if let Some(wait) = result.as_ref().err().and_then(Error::retry_after) {
    eprintln!("the API asks you to retry after {wait:?}");
}
match result {
    Ok(usage) => println!("{} allowance rows", usage.allowance.len()),
    // A refusal from the API: status, code (stable) and message (localised).
    Err(Error::Api(e)) => eprintln!("{} {} {}", e.status, e.code, e.message),
    // The token endpoint refused the credentials or the scopes.
    Err(Error::OAuth(e)) => eprintln!("{} {} {}", e.status, e.error, e.description.unwrap_or_default()),
    Err(Error::Maintenance(_)) => eprintln!("the API is under maintenance"),
    // No usable answer: connect, tls, reset, timeout, and so on.
    Err(Error::Transport(e)) => eprintln!("transport: {}", e.kind),
    Err(other) => return Err(other.into()),
}

呢頁包裝咗乜嘢