2 个版本
0.1.1 | 2020 年 9 月 18 日 |
---|---|
0.1.0 | 2020 年 9 月 17 日 |
#2 in #urban
20KB
149 代码行
urban-rs: Urban Dictionary 的 API
一个异步 API,用于与 Urban Dictionary 交互以获取定义。
API 使用 reqwest 从互联网上获取定义
有三种方式获取定义
- 按单词
- 按 ID
- 随机
示例
use std::io;
use tokio::runtime::Runtime;
println!("What word do you want defined?");
let mut word = String::new();
io::stdin()
.read_line(&mut word)
.expect("Failed to read line");
// A reqwest client is needed to use the urban API
let client = reqwest::Client::new();
// The function is async. Thus it needs an executor to be ran from inside a non-async
// function.
if let Ok(result) = Runtime::new()
.expect("Failed to create tokio runtime")
.block_on(urban_rs::fetch_definition(&client, &word))
{
// the result is a vector of definitions. If it has no length then there were no words
// found
if result.is_empty() {
println!("No words were found");
return;
}
let first_result = &result[0];
println!("Definition for {}:\n{}", first_result.word(), first_result.definition());
} else {
println!("An error has occured while fetching the definition");
}
此示例会要求用户输入一个单词,并打印出其定义
指南
要开始使用 urban-rs,请将其添加到您的 cargo.toml 中
urban-rs = "0.1.0"
Urban-rs 使用 reqwest
以异步方式通过互联网获取定义。
这意味着您需要使用一个 reqwest::Client
来提供给函数。用户提供客户端的原因是它可以跨多个函数调用重用。甚至可以跨不同的 API,所有这些 API 都需要 reqwest 客户端。
此外,由于函数是异步的,它们不会直接返回结果。但会返回一个需要执行的未来。使用 futures
的执行器不会工作。因为 reqwest 需要 tokios 运行时来执行。因此,从函数返回的未来需要通过 tokio
的 Runtime
和其执行器来调用。
use tokio::runtime::Runtime;
// A reqwest client is needed so that the Urban API can make web API calls
let client = reqwest::Client::new();
// As stated before. The API uses async functions which return futures. These need to be executed trough
// tokio's Runtime.
if let Ok(result) = Runtime::new()
.expect("Failed to create tokio runtime")
.block_on(urban_rs::fetch_random(&client))
{
// the result is a vector of definitions. If it has no length then there were no words
// found
if result.is_empty() {
println!("No words were found");
return;
}
let first_result = &result[0];
println!("Definition of the day: {}!\n{}", first_result.word(), first_result.definition());
} else {
println!("An error has occured while fetching the definition");
}
许可协议
依赖项
~4–8.5MB
~191K SLoC