当前位置:网站首页>[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 .
边栏推荐
- Leetcode 45 Jumping game II (2022.02.14)
- The first "mobile cloud Cup" empty publicity meeting, looking forward to working with developers to create a new world of computing!
- Basic number theory -- Gauss elimination
- [JS download files through url]
- Han Zhichao: real time risk control practice of eBay based on graph neural network
- Global and Chinese markets for context and location-based services 2022-2028: Research Report on technology, participants, trends, market size and share
- 【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)
- 学习笔记25--多传感器前融合技术
- GL Studio 5 安装与体验
- [WesternCTF2018]shrine writeup
猜你喜欢

You probably haven't noticed the very important testing strategy in your work

ACM教程 - 快速排序(常规 + 尾递归 + 随机基准数)

The first "mobile cloud Cup" empty publicity meeting, looking forward to working with developers to create a new world of computing!

【八大排序①】插入排序(直接插入排序、希尔排序)

技术大佬准备就绪,话题C位由你决定

Leetcode, 3 repeatless longest subsequence

浅浅了解Servlet

Hcip day 14 (MPLS protocol)

Advanced skills of testers: a guide to the application of unit test reports

Infiltration records of CFS shooting range in the fourth phase of the western regions' Dadu Mansion
随机推荐
[eight sorts ②] select sort (select sort, heap sort)
[IVX junior engineer training course 10 papers to get certificates] 0708 news page production
教你白嫖Amazon rds一年并搭建MySQL云数据库(只需10分钟,真香)
Tencent cloud techo youth dream campus trip into Wuhan University
No converter found for return value of type: class
Infiltration records of CFS shooting range in the fourth phase of the western regions' Dadu Mansion
Day 13 of hcip (relevant contents of BGP agreement)
UDS bootloader of s32kxxx bootloader
Cookie, session, tooken
Global and Chinese markets for maritime services 2022-2028: Research Report on technology, participants, trends, market size and share
Develop a simple login logic based on SSM
Based on Simulink and FlightGear, the dynamic control of multi rotor UAV in equilibrium is modeled and simulated
只是以消费互联网的方式和方法来落地和实践产业互联网,并不能够带来长久的发展
You probably haven't noticed the very important testing strategy in your work
Circular statements in shell programming
I'll teach you to visit Amazon RDS for a year and build a MySQL cloud database (only 10 minutes, really fragrant)
Sql--- related transactions
Design and control of multi rotor aircraft (VII) -- sensor calibration and measurement model
NeRV: Neural Reflectance and Visibility Fields for Relighting and View Synthesis
Variables and constants of go language foundation