initialize

This commit is contained in:
2025-09-04 16:36:08 +08:00
commit e6f937fe44
4 changed files with 1599 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

1529
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

8
Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[package]
name = "rust-backend"
version = "0.1.0"
edition = "2024"
[dependencies]
actix-web = "4.11.0"
serde = "1.0.219"

61
src/main.rs Normal file
View File

@@ -0,0 +1,61 @@
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
// 定义响应数据结构
#[derive(Serialize)]
struct GreetingResponse {
message: String,
}
// 定义请求数据结构
#[derive(Deserialize)]
struct UserRequest {
name: String,
age: u8,
}
// 健康检查端点
#[get("/health")]
async fn health_check() -> impl Responder {
HttpResponse::Ok().body("Service is healthy")
}
// 根路径处理
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok().body("Welcome to Rust Web Backend!")
}
// 带参数的问候端点
#[get("/greet/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
let response = GreetingResponse {
message: format!("Hello, {}!", name),
};
HttpResponse::Ok().json(response)
}
// POST 请求处理
#[post("/user")]
async fn create_user(user: web::Json<UserRequest>) -> impl Responder {
let response = GreetingResponse {
message: format!("Created user: {} (age {})", user.name, user.age),
};
HttpResponse::Created().json(response)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
println!("Starting server at http://localhost:8080");
HttpServer::new(|| {
App::new()
.service(health_check)
.service(index)
.service(greet)
.service(create_user)
})
.bind("127.0.0.1:8080")?
.run()
.await
}