当前位置:网站首页>[rust web rokcet Series 1] Hello, world and get, post, put, delete
[rust web rokcet Series 1] Hello, world and get, post, put, delete
2022-07-02 01:18:00 【Macaroni candy】
Rust Web Rokcet series 1 Hello,World! And GET,POST,PUT,DELETE
Original address : https://www.ftls.xyz/posts/rust-rocket1/
author : Macaroni candy
Series address : https://www.ftls.xyz/series/rust-web-rokcet
Rust web At present, there are several frameworks used more in the field , Such as actix-web, Rocket wait . I am using jwt Used in Rocket , Because it was originally used 0.5.0-rc.1 edition , When connecting to the database, I took some detours . So record this article to give later people a little reference .
actually , Documentation is also the most effective learning tool . Including when connecting to the database , Somewhat github Use on Rokcet v3 Written connection pool . And in the Rokcet 0.5.0-rc.1 Version provides related tools , One line of code can use connection pooling . The specific use depends on the document .
documentation :
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\
First, add dependencies , First add a frame .
rocket = { version = "0.5.0-rc.1",features = ["json"]}
stay src/main.rs write in
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
And then run cargo run , visit http://127.0.0.1:8000 You can see that Hello, world! 了 .


GET/POST/PUT/DELETE
establish src\module.rs , Create the required structure . We need to pay attention to , What we use here is rocket Serialization and deserialization tools provided .
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,
}
Next , Create a src\routes.rs . hold Request to be placed uniformly routes.rs in . And then again main.rs Quoted in Li . Implement the basic get,post,delect,put. Here is the code
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: " Macaroni candy ".to_string(),
content: " Some 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 })
}
to update main.rs, function cargo fmt formatting code . then cargo run Run code .
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])
}
test
Use Postman test , Can operate normally .
Postman Import :
You can test .
边栏推荐
- Global and Chinese markets for distributed generation and energy storage in telecommunications networks 2022-2028: Research Report on technology, participants, trends, market size and share
- 学习笔记24--多传感器后融合技术
- Infiltration records of CFS shooting range in the fourth phase of the western regions' Dadu Mansion
- 6-3 vulnerability exploitation SSH environment construction
- Zak's latest "neural information transmission", with slides and videos
- S32Kxxx bootloader之UDS bootloader
- [IVX junior engineer training course 10 papers to get certificates] 01 learn about IVX and complete the New Year greeting card
- How to reflect and solve the problem of bird flight? Why are planes afraid of birds?
- What skills does an excellent software tester need to master?
- [WesternCTF2018]shrine writeup
猜你喜欢

Excel PivotTable

Evolution of Himalayan self-developed gateway architecture

Recommend an online interface mock tool usemock

GL Studio 5 安装与体验

How to compress video size while adding watermark with one click?

Geek DIY open source solution sharing - digital amplitude frequency equalization power amplifier design (practical embedded electronic design works, comprehensive practice of software and hardware)

学习笔记25--多传感器前融合技术

6-3漏洞利用-SSH环境搭建

教你白嫖Amazon rds一年并搭建MySQL云数据库(只需10分钟,真香)

ACM tutorial - quick sort (regular + tail recursion + random benchmark)
随机推荐
学习笔记24--多传感器后融合技术
cookie、session、tooken
[conference resources] the Third International Conference on Automation Science and Engineering in 2022 (jcase 2022)
6-3漏洞利用-SSH环境搭建
Excel search and reference function
Luogu p1775 stone merger (weakened version)
2022年6月国产数据库大事记
Recently, three articles in the nature sub Journal of protein and its omics knowledge map have solved the core problems of biology
Creation of volume group for AIX storage management (I)
You probably haven't noticed the very important testing strategy in your work
Datawhale community blackboard newspaper (issue 1)
Two TVs
Global and Chinese market of collaborative applications 2022-2028: Research Report on technology, participants, trends, market size and share
SSO single sign on implementation.
Basic number theory -- Gauss elimination
S32Kxxx bootloader之UDS bootloader
Learning note 3 -- Key Technologies of high-precision map (Part 1)
Global and Chinese markets of digital crosspoint switches and mux/demux 2022-2028: Research Report on technology, participants, trends, market size and share
A problem about function template specialization
SAP ui5 beginner tutorial XXI - trial version of custom formatter of SAP ui5