实现RESTful API服务
项目依赖
[dependencies]
# 一个模块化的web应用程序框架
axum = "0.7.2"
# 一个事件驱动的非阻塞I/O库
tokio = { version = "1.35.1", features = ["full"] }
# http client
reqwest = "0.11.23"
# 日志抽象
log = "0.4.20"
# 日志实现
simple_logger = "4.3.0"
# 序列化
serde = { version = "1.0", features = ["derive"] }
# json序列化
serde_json = "1.0.68"
创建一个http server
# src/main.rs
// 引入模块
use axum::{
http::StatusCode,
response::{Html, IntoResponse, Json},
routing::{get, post},
Router,
};
use log::{debug, info, trace, warn};
use serde::{Deserialize, Serialize};
use serde_json::json;
use simple_logger::SimpleLogger;
#[tokio::main]
async fn main() {
// 初始化日志组件
SimpleLogger::new().init().unwrap();
debug!("power by iovhm.com");
warn!("©copyRight");
trace!("2023年12月27日");
info!("application start");
let app = Router::new()
// GET / 首页
.route("/", get(root));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
info!("server listen at 0.0.0.0:3000");
axum::serve(listener, app).await.unwrap();
}
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u32,
}
async fn root() -> impl IntoResponse {
info!("entry root");
// 创建一个匿名的JSON对象
let json_obj = json!({"name": "John Doe", "age": 30});
return Json(json_obj);
}