初识 rust的web框架
hello-world
#新建项目
cargo new hello-world
#进入项目
cd hello-world
Cargo.toml文件中加如下内容
[dependencies]
actix-web = "4"
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hey there!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
.service(echo)
.route("/hey", web::get().to(manual_hello))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
# 访问地址:GET 请求
http://127.0.0.1:8080/
# 访问地址:GET 请求
http://127.0.0.1:8080/hey
# 访问地址:post请求 请求体{}
http://127.0.0.1:8080/echo
访问html
具有一个路由的多个资源将被注册用于相同的资源路径。
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().service(
// prefixes all resources and routes attached to it...
web::scope("/app")
// ...so this handles requests for `GET /app/index.html`
.route("/index.html", web::get().to(index)),
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
# 访问地址:GET 请求
http://127.0.0.1:8080/app/index.html