当前位置:网站首页>[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 .
边栏推荐
- [JS download files through url]
- We should make clear the branch prediction
- Global and Chinese market of wireless charging magnetic discs 2022-2028: Research Report on technology, participants, trends, market size and share
- What are the differences between software testers with a monthly salary of 7K and 25K? Leaders look up to you when they master it
- LeetCode、3无重复最长子序列
- Comprehensive broadcast of global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
- Appium inspector can directly locate the WebView page. Does anyone know the principle
- Bilstm CRF code implementation
- XMIND mind map
- Entrepreneurship is a little risky. Read the data and do a business analysis
猜你喜欢

How can I batch produce the same title for the video?

学习笔记3--高精度地图关键技术(上)

Design and control of multi rotor aircraft (VII) -- sensor calibration and measurement model

Based on Simulink and FlightGear, the dynamic control of multi rotor UAV in equilibrium is modeled and simulated
![[IVX junior engineer training course 10 papers to get certificates] 03 events and guessing numbers games](/img/69/44219af52baef20cedec3870147589.jpg)
[IVX junior engineer training course 10 papers to get certificates] 03 events and guessing numbers games

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

Iclr2022 | spherenet and g-spherenet: autoregressive flow model for 3D molecular graph representation and molecular geometry generation

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

Keepalived introduction and installation

Learning notes 25 - multi sensor front fusion technology
随机推荐
Basic usage of three JS high-order functions --filter---map---reduce
What are the differences between software testers with a monthly salary of 7K and 25K? Leaders look up to you when they master it
The author is more willing to regard industrial Internet as a concept much richer than consumer Internet
Leetcode, 3 repeatless longest subsequence
【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)
Global and Chinese market of aircraft MRO software 2022-2028: Research Report on technology, participants, trends, market size and share
测试员8年工资变动,令网友羡慕不已:你一个月顶我一年工资
Minimize the error
NeRV: Neural Reflectance and Visibility Fields for Relighting and View Synthesis
Evolution of Himalayan self-developed gateway architecture
Bubble Sort Graph
XMind思维导图
LeetCode、3无重复最长子序列
MySQL application day02
SSO single sign on implementation.
[IVX junior engineer training course 10 papers] 05 canvas and aircraft war game production
Global and Chinese markets for food allergens and intolerance tests 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets of beverage seasoning systems 2022-2028: Research Report on technology, participants, trends, market size and share
关于ASP.NET CORE使用DateTime日期类型参数的一个小细节
Global and Chinese market of wireless charging magnetic discs 2022-2028: Research Report on technology, participants, trends, market size and share