跨域中间件
2025年10月22日小于 1 分钟hyperlanewebrustmiddlewaremulti-server
跨域中间件
原生写法
use hyperlane::*;
struct CrossMiddleware;
struct IndexRoute;
struct ResponseMiddleware;
impl ServerHook for CrossMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
ctx.set_response_version(HttpVersion::HTTP1_1)
.await
.set_response_header(ACCESS_CONTROL_ALLOW_ORIGIN, WILDCARD_ANY)
.await
.set_response_header(ACCESS_CONTROL_ALLOW_METHODS, ALL_METHODS)
.await
.set_response_header(ACCESS_CONTROL_ALLOW_HEADERS, WILDCARD_ANY)
.await;
}
}
impl ServerHook for IndexRoute {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
ctx.set_response_status_code(200)
.await
.set_response_body("Hello, world!")
.await;
}
}
impl ServerHook for ResponseMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
ctx.send().await.unwrap();
}
}
#[tokio::main]
async fn main() {
Server::new()
.await
.request_middleware::<CrossMiddleware>()
.await
.response_middleware::<ResponseMiddleware>()
.await
.route::<IndexRoute>("/")
.await
.run()
.await
.unwrap()
.wait()
.await
}
宏写法
use hyperlane::*;
use hyperlane_utils::*;
#[request_middleware(1)]
struct CrossMiddleware;
#[route("/")]
struct IndexRoute;
#[response_middleware(1)]
struct ResponseMiddleware;
impl ServerHook for CrossMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
#[response_version(HttpVersion::HTTP1_1)]
#[response_header(ACCESS_CONTROL_ALLOW_ORIGIN, WILDCARD_ANY)]
#[response_header(ACCESS_CONTROL_ALLOW_METHODS, ALL_METHODS)]
#[response_header(ACCESS_CONTROL_ALLOW_HEADERS, WILDCARD_ANY)]
async fn handle(self, ctx: &Context) {}
}
impl ServerHook for IndexRoute {
async fn new(_ctx: &Context) -> Self {
Self
}
#[response_status_code(200)]
#[response_body("Hello, world!")]
async fn handle(self, ctx: &Context) {}
}
impl ServerHook for ResponseMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
#[send]
async fn handle(self, ctx: &Context) {}
}
#[tokio::main]
async fn main() {
Server::new().await.run().await.unwrap().wait().await
}