示例

01-introduction/02-example.md
commit - 594b37d6bb98a7f39e7596f457ffcb83fd160b86 - 2021.01.04

下面的示例中,将创建 HTTP 服务器,接收 JSON 文本,对其进行验证,并用确认消息进行响应。

use tide::prelude::*;
use tide::Request;

#[derive(Debug, Deserialize)]
struct Animal {
    name: String,
    legs: u8,
}

#[async_std::main]
async fn main() -> tide::Result<()> {
    tide::log::start();
    let mut app = tide::new();

    app.at("/orders/shoes").post(order_shoes);
    app.listen("127.0.0.1:8080").await?;

    Ok(())
}

async fn order_shoes(mut req: Request<()>) -> tide::Result {
    let Animal { name, legs } = req.body_json().await?;
    Ok(format!("Hello, {}! I've put in an order for {} shoes", name, legs).into())
}

执行如下命令:

$ curl localhost:8080/orders/shoes -d '{ "name": "Chashu", "legs": 4 }'

输出如下响应信息:

Hello, Chashu! I've put in an order for 4 shoes

执行如下命令:

$ curl localhost:8080/orders/shoes -d '{ "name": "Mary Millipede", "legs": 750 }'

将没有响应信息,因为数字太大,无法放入目标类型。