Web服务开发 #

一、基本服务 #

rust
use actix_web::{web, App, HttpServer, Responder};

async fn index() -> impl Responder {
    "Hello, World!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

二、路由参数 #

rust
use actix_web::{web, HttpResponse};

async fn user_info(path: web::Path<(u32,)>) -> HttpResponse {
    let user_id = path.0;
    HttpResponse::Ok().body(format!("User ID: {}", user_id))
}

三、JSON处理 #

rust
use actix_web::{web, HttpResponse};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    email: String,
}

async fn create_user(user: web::Json<User>) -> HttpResponse {
    HttpResponse::Ok().json(user.0)
}

四、总结 #

本章学习了:

  • actix-web 基本使用
  • 路由定义
  • JSON处理
最后更新:2026-03-27