MST

星途 面试题库

面试题:Rust中搭建Web服务器基础路由实现

在Rust中使用`actix - web`框架搭建一个简单的Web服务器,要求实现两个路由:一个是根路由`/`,返回'Hello, World!';另一个是`/about`路由,返回关于这个Web服务器的简单描述。请给出完整的代码实现。
42.1万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};

// 根路由处理函数
#[get("/")]
async fn index() -> impl Responder {
    HttpResponse::Ok().body("Hello, World!")
}

// /about路由处理函数
#[get("/about")]
async fn about() -> impl Responder {
    HttpResponse::Ok().body("This is a simple web server built with actix - web in Rust.")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
          .service(index)
          .service(about)
    })
  .bind("127.0.0.1:8080")?
  .run()
  .await
}