Axum是一个用于编写异步HTTP服务的Rust框架,可以通过以下代码示例中的方式使用HTTP/2:
[dependencies]
axum = { version = "0.1.6", features = ["http2"] }
hyper = "0.14.10"
http::Server
改为axum::Server
,并将HTTP协议版本设置为HTTP/2。以下是一个示例:use axum::{prelude::*, response::IntoResponse};
use hyper::http::{Response, StatusCode};
async fn api_handler() -> impl IntoResponse {
Response::builder()
.status(StatusCode::OK)
.body("Hello, Axum!")
.unwrap()
}
#[tokio::main]
async fn main() {
let app = route("/", get(api_handler))
.route("/hello", get(|| async { "Hello, World!" }));
let addr = "127.0.0.1:3000".parse().unwrap();
axum::Server::bind(&addr)
.http2_only(true) // 开启HTTP/2
.serve(app.into_make_service())
.await
.unwrap();
}
以上就是Axum中使用HTTP/2的解决方法,通过修改代码和添加依赖即可实现启用HTTP/2。