1 Star 0 Fork 0

恐咖兵糖/www.ftls.xyz

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
2022-02-14-rust-rocket1.md 4.42 KB
一键复制 编辑 原始数据 按行查看 历史
恐咖兵糖 提交于 2024-02-24 17:21 . pref: 修改分类
title: "Rust Web Rokcet 系列 1 Hello,World!与 GET,POST,PUT,DELETE"
subtitle: ""
slug: "rust-rocket1"
date: 2022-02-14T13:17:43+08:00
lastmod: 2022-02-14T13:17:43+08:00
draft: false
description: ""

tags: ["Rust","Web","Rocket"]
categories: ["Rust"]

featuredImage: ""
featuredImagePreview: ""

hiddenFromHomePage: false

lightgallery: true

series: ["Rust Web Rokcet"]
series_weight: 1

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

Hello,World!

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

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

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

在 src/main.rs 写入

#[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! 了。

{{< image src="https://cdn.ftls.xyz/images/2022/02/20220214121227.png" caption="源代码" >}} {{< image src="https://cdn.ftls.xyz/images/2022/02/20220214121549.png" caption="Postman 测试" >}}

GET/POST/PUT/DELETE

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

src\module.rs

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

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

#[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

就可以测试了。

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/kkbt/www.ftls.xyz.git
git@gitee.com:kkbt/www.ftls.xyz.git
kkbt
www.ftls.xyz
www.ftls.xyz
master

搜索帮助

Cb406eda 1850385 E526c682 1850385