Rust使用poem框架初体验


Poem介绍

Poem是一个基于tokio/hyper的WEB服务端框架。属于一个比较新的rust框架,功能比较齐全而且便于上手,作为一个rust新手使用该框架实现功能来了解rust和poem,看一看使用效果如何。项目地址:https://github.com/poem-web/poem

1.main

首先需要在Cargo.toml中的依赖项下添加 poem = "1.3.38" tokio = { version = "1.20.1", features = ["full"] }

在main.rs文件中添加一个接口处理handler函数

#[handler]
fn return_str() -> &'static str {
    "hello"
}

然后设置main函数

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    let app = Route::new().at("/hello", get(return_str));
    Server::new(TcpListener::bind("127.0.0.1:3000"))
        .run(app)
        .await
}

上面就是服务的启动以及设置路由,然后设置get请求handler等操作,是很简单的,至于tokio以及异步函数,以后再详细了解。

2.post请求

需要用到serde,所以在Cargo.toml中添加serde serde = "1.0.143"

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize)]
pub struct Params {
    name: String,
}

#[handler]
pub fn index(res: Result<Query<Params>>) -> Result<impl IntoResponse> {
    match res {
        Ok(Query(params)) => Ok(params.name.into_response()),
        Err(err) if err.is::<ParseQueryError>() => Ok(Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .body(err.to_string())),
        Err(err) => Err(err),
    }
}

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    let app = Route::new()
        .at("/hello", get(return_str))
        .at("/index", post(index));
    Server::new(TcpListener::bind("127.0.0.1:3000"))
        .run(app)
        .await
}

3. 引用同级文件夹下的函数

在main.rs同级文件下新建一个api文件夹,文件夹下新建api.rs文件,里面有一个函数

#[derive(Debug, Deserialize)]
pub struct User {
    name: String,
}

#[derive(Serialize, Deserialize)]
pub struct UserResp {
    code: u8,
    message: String,
}

#[handler]
pub fn new_user(user: Json<User>) -> Json<UserResp> {
    let u = user.name.to_string();
    return Json(UserResp {
        code: 200,
        message: u,
    });
}

但是这个时候在main.rs中还无法使用,需要在api文件夹下新建一个mod.rs,内容为:

pub mod api;
pub use api::new_user;

将这个文件夹和其中函数暴露出来,具体的mod介绍,以后再详细介绍。
这个时候只需要在main.rs中添加 mod api; 就可以使用api文件夹中的new_user函数了.

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    let app = Route::new()
        .at("/hello", get(return_str))
        .at("/index", get(api::index))
        .at("/index", get(api::new_user))
        .with(Tracing); // 追踪
    Server::new(TcpListener::bind("127.0.0.1:3000"))
        .run(app)
        .await
}

小结

这篇博客只是关于poem的傻瓜是教程,并没有对rust和poem中的知识进行深究,由于自身也是rust小白,所以也算做一种学习记录,更多相关的内容会在之后的不断学习中深入了解。


文章作者: GoldThree
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 GoldThree !