Rust Web Rokcet 系列 1 Hello,World!与 GET,POST,PUT,DELETE

系列 - Rust Web Rokcet

Rust web 领域目前有几个使用较多的框架,如 actix-web, Rocket 等等。我在使用 jwt 时使用过 Rocket ,由于最初使用的是 0.5.0-rc.1 版本,连接数据库的时候走了一些弯路。因此记录这篇文章给后来的人一点借鉴。

实际上,文档还是最有效的学习工具。包括连接数据库时,有一些 github 上的使用 Rokcet v3 写的连接池。而在 Rokcet 0.5.0-rc.1 版本提供了相关工具,一行代码就可以使用连接池。具体使用还是要看文档的。

文档资料:

Rocket - Simple, Fast, Type-Safe Web Framework for Rust

Quickstart - Rocket Programming Guide

1
2
3
PS D:\cms> cargo new teach_used
     Created binary (application) `teach_used` package
PS D:\cms> code .\teach_used\

首先添加依赖,先添加一个框架。

1
rocket = { version = "0.5.0-rc.1",features = ["json"]}

在 src/main.rs 写入

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

然后运行 cargo run ,访问 http://127.0.0.1:8000 就可以看到 Hello, world! 了。

https://cdn.ftls.xyz/images/2022/02/20220214121227.png
源代码

https://cdn.ftls.xyz/images/2022/02/20220214121549.png
Postman 测试

创建 src\module.rs , 创建需要的结构体。需要注意,这里使用的是 rocket 提供的序列化和反序列化工具。

src\module.rs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use rocket::serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(crate = "rocket::serde")]
pub struct Article {
    pub id: usize,
    pub title: String,
    pub author: String,
    pub content: String,
    pub created_at: String,
}

接下来,创建一个 src\routes.rs 。把 请求统一放在 routes.rs 里。然后再 main.rs 里引用。实现基本的get,post,delect,put。下面是代码

src\routes.rs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use rocket::serde::json::{serde_json::json, Json, Value};
use rocket::{delete, get, post, put};

use crate::module::Article;

#[get("/")]
pub fn index() -> &'static str {
    "Hello, world!"
}

#[get("/api")]
pub async fn get_article_list() -> Value {
    json!({"res": "Test Success!"})
}

#[get("/api/<in_id>")]
pub async fn get_article_by_id(in_id: usize) -> Option<Json<Article>> {
    Some(Json(Article {
        id: in_id,
        title: "a title".to_string(),
        author: "恐咖兵糖".to_string(),
        content: "一些内容".to_string(),
        created_at: "2022-02-14 ".to_string(),
    }))
}

#[post("/api", format = "json", data = "<article>")]
pub async fn post_article(article: Json<Article>) -> Value {
    json!({"res": "Post Success!","post": format!("{:?}", article) })
}

#[put("/api/<in_id>", format = "json", data = "<article>")]
pub async fn put_article(in_id: usize, article: Json<Article>) -> Value {
    json!({"res": "Put Success!","id": in_id,"put": format!("{:?}",article) })
}

#[delete("/api/<in_id>")]
pub async fn delete_article(in_id: usize) -> Value {
    json!({"res": "Delect Success","id": in_id })
}

更新 main.rs, 运行 cargo fmt 格式化代码。然后 cargo run 运行代码。

src\main.rs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#[macro_use]
extern crate rocket;

mod module;
mod routes;

use routes::*;

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index])
        // add api
        .mount("/", routes![get_article_list, get_article_by_id])
        .mount("/", routes![post_article, delete_article, put_article])
}

使用 Postman 测试,均可以正常运行。

Postman 导入:

teach.postman_collection.json

就可以测试了。