feat: add middleware implementation

This commit is contained in:
yangshangbo
2025-07-04 16:23:53 +08:00
parent 3764a640c4
commit fd9d2cbbfa
2 changed files with 29 additions and 2 deletions
+6
View File
@@ -101,6 +101,12 @@ fn main() {
} }
}) })
// 日志打印中间件示例
app.use(fn (mut req hono.Request, next fn (mut hono.Request) http.Response) http.Response {
println('[LOG] ${req.url}')
return next(mut req)
})
println('Server starting on :8080') println('Server starting on :8080')
println('测试静态路由: http://localhost:8080/') println('测试静态路由: http://localhost:8080/')
println('测试健康检查: http://localhost:8080/api/health') println('测试健康检查: http://localhost:8080/api/health')
+23 -2
View File
@@ -26,6 +26,7 @@ mut:
pub mut: pub mut:
hybrid_router HybridRouter hybrid_router HybridRouter
trie_router TrieRouter trie_router TrieRouter
middlewares []Middleware
} }
pub fn (mut app Hono) get(path string, handler fn (Request) http.Response) { pub fn (mut app Hono) get(path string, handler fn (Request) http.Response) {
@@ -87,6 +88,12 @@ fn server_hanler_new(app Hono) ServerHanler {
} }
} }
type Middleware = fn (mut req Request, next fn (mut Request) http.Response) http.Response
pub fn (mut app Hono) use(mw Middleware) {
app.middlewares << mw
}
fn (mut s ServerHanler) handle(req http.Request) http.Response { fn (mut s ServerHanler) handle(req http.Request) http.Response {
mut res := http.Response{ mut res := http.Response{
status_code: 404 status_code: 404
@@ -111,17 +118,31 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
// body // body
body := req.data body := req.data
// 构造 hono.Request // 构造 hono.Request
hreq := Request{ mut hreq := Request{
url: url.path url: url.path
param: param_map param: param_map
query: query_map query: query_map
body: body body: body
} }
res = route_match.handler.handle(hreq) // 洋葱模型递归执行中间件
return s.exec_middlewares(0, mut hreq, fn [route_match] (req Request) http.Response {
return route_match.handler.handle(req)
})
} }
return res return res
} }
fn (mut s ServerHanler) exec_middlewares(idx int, mut req Request, handler fn (Request) http.Response) http.Response {
if idx < s.app.middlewares.len {
mw := s.app.middlewares[idx]
return mw(mut req, fn [mut s, idx, handler] (mut r Request) http.Response {
return s.exec_middlewares(idx+1, mut r, handler)
})
} else {
return handler(req)
}
}
pub fn (mut app Hono) listen(port string) { pub fn (mut app Hono) listen(port string) {
app.server.addr = port app.server.addr = port
app.server.handler = server_hanler_new(app) app.server.handler = server_hanler_new(app)