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()),
}

本頁封裝的內容