Rust项目入门,包含项目的基本搭建,如何使用Rocket框架以及使用Rocket框架设置路由,如何处理GET POST请求,以及返回JSON格式数据.
新建项目
cargo new rocket-web --bin
使用Rocket框架 GET请求
#![feature(decl_macro)]
#[macro_use]
extern crate rocket;
use rocket::Request;
use rocket_contrib::json::Json;
fn main() {
rocket::ignite()
.mount("/api", routes![hello])
.launch();
}
#[get("/hello")]
fn hello() -> Json<&'static str> {
Json(
"{
'status': 'success',
'message': 'Hello API!'
}",
)
}
POST请求 json格式
#[allow(dead_code)]
#[derive(Serialize, Deserialize, Debug)]
pub struct User {
name: String,
}
#[allow(dead_code)]
#[derive(Serialize, Deserialize)]
pub struct UserResp {
code: u8,
message: String,
}
#[post("/user", format = "json", data = "<user>")]
fn new_user(user: Json<User>) -> Json<UserResp> {
let u = user.into_inner();
let mut dummy_db: Vec<User> = Vec::new();
dummy_db.push(u);
return Json(UserResp {
code: 200,
message: "succeed".to_string(),
});
}
上面代码中展示了如何处理post接口,需要注意的是,当数据类型不是json的格式时候,不会被该函数处理;
定义了请求数据格式和返回数据格式;
最后需要在main函数中添加路由即可
fn main() {
rocket::ignite()
.mount("/api", routes![hello, new_user])
.launch();
}
添加依赖
可以使用cargo add xxx
,例如:cargo add rand