当前位置:网站首页>[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 market of avionics systems 2022-2028: Research Report on technology, participants, trends, market size and share
- [IVX junior engineer training course 10 papers to get certificates] 0708 news page production
- 2022年6月国产数据库大事记
- Mathematics - feelings -20220215
- Cookie, session, tooken
- No converter found for return value of type: class
- How does schedulerx help users solve the problem of distributed task scheduling?
- Advanced skills of testers: a guide to the application of unit test reports
- How to reflect and solve the problem of bird flight? Why are planes afraid of birds?
- We should make clear the branch prediction
猜你喜欢

How does schedulerx help users solve the problem of distributed task scheduling?

How to reflect and solve the problem of bird flight? Why are planes afraid of birds?

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

I'll teach you to visit Amazon RDS for a year and build a MySQL cloud database (only 10 minutes, really fragrant)

Exclusive delivery of secret script move disassembly (the first time)

Edge computing accelerates live video scenes: clearer, smoother, and more real-time

Hcip day 14 (MPLS protocol)

How to compress video size while adding watermark with one click?
![[IVX junior engineer training course 10 papers to get certificates] 09 chat room production](/img/a8/25215e74162b7ab3f29df65681932b.jpg)
[IVX junior engineer training course 10 papers to get certificates] 09 chat room production
![[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)](/img/c2/7ebc67e9b886e3baf3c98489bf9bce.png)
[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)
随机推荐
The 8-year salary change of testers makes netizens envy it: you pay me one year's salary per month
笔者更加愿意将产业互联网看成是一个比消费互联网要丰富得多的概念
[IVX junior engineer training course 10 papers] 06 database and services
Part 29 supplement (XXIX) basis of ECMAScript
Global and Chinese markets for the application of artificial intelligence in security, public security and national security 2022-2028: Research Report on technology, participants, trends, market size
[IVX junior engineer training course 10 papers to get certificates] 01 learn about IVX and complete the New Year greeting card
SAP ui5 beginner tutorial XXI - trial version of custom formatter of SAP ui5
CEPH buffer yyds dry inventory
[disease detection] realize lung cancer detection system based on BP neural network, including GUI interface
学习笔记2--高精度地图定义及价值
Bilstm CRF code implementation
Single chip microcomputer -- hlk-w801 transplant NES simulator (III)
Recently, three articles in the nature sub Journal of protein and its omics knowledge map have solved the core problems of biology
CTF daily question day45 sensor
How to determine whether the current script is in the node environment or the browser environment?
站在新的角度来看待产业互联网,并且去寻求产业互联网的正确方式和方法
Mathematics - feelings -20220215
No converter found for return value of type: class
Datawhale community blackboard newspaper (issue 1)
Cookie, session, tooken