身份校验中间件
2025年10月20日大约 1 分钟hyperlanewebrustmiddlewareauth
身份校验中间件
原生写法
use hyperlane::*;
struct HttpVersionMiddleware;
struct AuthMiddleware;
struct IndexRoute;
struct ResponseMiddleware;
impl ServerHook for HttpVersionMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
ctx.set_response_version(HttpVersion::HTTP1_1).await;
}
}
impl ServerHook for AuthMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
let auth_str: String = ctx
.try_get_request_header_back(AUTHORIZATION)
.await
.unwrap_or_default();
if auth_str.is_empty() {
ctx.set_response_status_code(401)
.await
.set_response_body("Unauthorized")
.await
.send()
.await
.unwrap();
ctx.aborted().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::<HttpVersionMiddleware>()
.await
.request_middleware::<AuthMiddleware>()
.await
.response_middleware::<ResponseMiddleware>()
.await
.route::<IndexRoute>("/")
.await
.run()
.await
.unwrap()
.wait()
.await
}
宏写法
use hyperlane::*;
use hyperlane_utils::*;
#[request_middleware(1)]
struct HttpVersionMiddleware;
#[request_middleware(2)]
struct AuthMiddleware;
#[route("/")]
struct IndexRoute;
#[response_middleware(1)]
struct ResponseMiddleware;
impl ServerHook for HttpVersionMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
#[response_version(HttpVersion::HTTP1_1)]
async fn handle(self, ctx: &Context) {}
}
impl ServerHook for AuthMiddleware {
async fn new(_ctx: &Context) -> Self {
Self
}
#[request_header(AUTHORIZATION => auth_str_opt)]
async fn handle(self, ctx: &Context) {
let auth_str: String = auth_str_opt.unwrap_or_default();
if auth_str.is_empty() {
ctx.set_response_status_code(401)
.await
.set_response_body("Unauthorized")
.await
.send()
.await
.unwrap();
ctx.aborted().await;
}
}
}
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
}