Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9aefe5714d | ||
|
|
1fc22044c3 | ||
|
|
b478269d8e | ||
|
|
69d1385ced | ||
|
|
1482b9c4d9 |
@@ -40,6 +40,10 @@ pub mut:
|
|||||||
use_fast_router bool = true // 新增:是否使用快速路由器
|
use_fast_router bool = true // 新增:是否使用快速路由器
|
||||||
context_middlewares []ContextMiddleware
|
context_middlewares []ContextMiddleware
|
||||||
route_middlewares map[string][]ContextMiddleware // 路由前缀对应的中间件
|
route_middlewares map[string][]ContextMiddleware // 路由前缀对应的中间件
|
||||||
|
// 优化:预排序的中间件前缀列表(启动时计算一次)
|
||||||
|
sorted_middleware_prefixes []string
|
||||||
|
// 优化:标记是否有中间件(用于零中间件快速路径)
|
||||||
|
has_middlewares bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Context 中间件类型
|
// Context 中间件类型
|
||||||
@@ -185,6 +189,14 @@ pub fn (mut app Hono) all(path string, handler fn (mut Context) http.Response) {
|
|||||||
// Context 中间件
|
// Context 中间件
|
||||||
pub fn (mut app Hono) use(mw ContextMiddleware) {
|
pub fn (mut app Hono) use(mw ContextMiddleware) {
|
||||||
app.context_middlewares << mw
|
app.context_middlewares << mw
|
||||||
|
app.has_middlewares = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 预计算中间件前缀排序(在服务器启动前调用)
|
||||||
|
pub fn (mut app Hono) precompute_middleware_prefixes() {
|
||||||
|
app.sorted_middleware_prefixes = app.route_middlewares.keys()
|
||||||
|
app.sorted_middleware_prefixes.sort(a.len < b.len)
|
||||||
|
app.has_middlewares = app.context_middlewares.len > 0 || app.route_middlewares.len > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// notFound() - 自定义 404 处理器
|
// notFound() - 自定义 404 处理器
|
||||||
@@ -215,25 +227,31 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析 query
|
// 解析 query - 优化:直接使用 url.raw_query 避免额外解析
|
||||||
raw_query := url.query().to_map()
|
|
||||||
mut query_map := map[string]string{}
|
mut query_map := map[string]string{}
|
||||||
for key, values in raw_query {
|
if url.raw_query.len > 0 {
|
||||||
if values.len > 0 {
|
query_map = parse_query_string_app(url.raw_query)
|
||||||
query_map[key] = values[0]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 缓存 method 字符串,避免多次调用 .str()
|
||||||
|
method_str := req.method.str()
|
||||||
|
|
||||||
// 尝试 Context 路由
|
// 尝试 Context 路由
|
||||||
// 优先使用快速路由器
|
// 优先使用快速路由器
|
||||||
if s.app.use_fast_router {
|
if s.app.use_fast_router {
|
||||||
if route_match := s.app.fast_router.match_route(req.method.str(), url.path) {
|
if route_match := s.app.fast_router.match_route(method_str, url.path) {
|
||||||
// param 由路由匹配结果提供
|
// param 由路由匹配结果提供
|
||||||
param_map := route_match.params.clone()
|
param_map := route_match.params.clone()
|
||||||
// body
|
// body
|
||||||
body := req.data
|
body := req.data
|
||||||
// 构造 Context
|
// 构造 Context
|
||||||
mut ctx := Context.new(req, param_map, query_map, body)
|
mut ctx := Context.new(req, param_map, query_map, body)
|
||||||
|
|
||||||
|
// 优化:零中间件快速路径
|
||||||
|
if !s.app.has_middlewares {
|
||||||
|
return route_match.handler.handle(mut ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// 获取该路径对应的中间件
|
// 获取该路径对应的中间件
|
||||||
middlewares := s.get_middlewares_for_path(url.path)
|
middlewares := s.get_middlewares_for_path(url.path)
|
||||||
// 洋葱模型递归执行中间件
|
// 洋葱模型递归执行中间件
|
||||||
@@ -243,13 +261,19 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 如果快速路由器没有匹配,回退到混合路由器
|
// 如果快速路由器没有匹配,回退到混合路由器
|
||||||
if route_match := s.app.context_hybrid_router.match_route(req.method.str(), url.path) {
|
if route_match := s.app.context_hybrid_router.match_route(method_str, url.path) {
|
||||||
// param 由路由匹配结果提供
|
// param 由路由匹配结果提供
|
||||||
param_map := route_match.params.clone()
|
param_map := route_match.params.clone()
|
||||||
// body
|
// body
|
||||||
body := req.data
|
body := req.data
|
||||||
// 构造 Context
|
// 构造 Context
|
||||||
mut ctx := Context.new(req, param_map, query_map, body)
|
mut ctx := Context.new(req, param_map, query_map, body)
|
||||||
|
|
||||||
|
// 优化:零中间件快速路径
|
||||||
|
if !s.app.has_middlewares {
|
||||||
|
return route_match.handler.handle(mut ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// 获取该路径对应的中间件
|
// 获取该路径对应的中间件
|
||||||
middlewares := s.get_middlewares_for_path(url.path)
|
middlewares := s.get_middlewares_for_path(url.path)
|
||||||
// 洋葱模型递归执行中间件
|
// 洋葱模型递归执行中间件
|
||||||
@@ -258,13 +282,19 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if route_match := s.app.context_hybrid_router.match_route(req.method.str(), url.path) {
|
if route_match := s.app.context_hybrid_router.match_route(method_str, url.path) {
|
||||||
// param 由路由匹配结果提供
|
// param 由路由匹配结果提供
|
||||||
param_map := route_match.params.clone()
|
param_map := route_match.params.clone()
|
||||||
// body
|
// body
|
||||||
body := req.data
|
body := req.data
|
||||||
// 构造 Context
|
// 构造 Context
|
||||||
mut ctx := Context.new(req, param_map, query_map, body)
|
mut ctx := Context.new(req, param_map, query_map, body)
|
||||||
|
|
||||||
|
// 优化:零中间件快速路径
|
||||||
|
if !s.app.has_middlewares {
|
||||||
|
return route_match.handler.handle(mut ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// 获取该路径对应的中间件
|
// 获取该路径对应的中间件
|
||||||
middlewares := s.get_middlewares_for_path(url.path)
|
middlewares := s.get_middlewares_for_path(url.path)
|
||||||
// 洋葱模型递归执行中间件
|
// 洋葱模型递归执行中间件
|
||||||
@@ -291,15 +321,17 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取路径对应的所有中间件(全局 + 路由前缀匹配的)
|
// 获取路径对应的所有中间件(全局 + 路由前缀匹配的)- 优化版
|
||||||
fn (s ServerHanler) get_middlewares_for_path(path string) []ContextMiddleware {
|
fn (s ServerHanler) get_middlewares_for_path(path string) []ContextMiddleware {
|
||||||
|
// 优化:只有全局中间件时,直接返回引用(避免克隆)
|
||||||
|
if s.app.route_middlewares.len == 0 {
|
||||||
|
return s.app.context_middlewares
|
||||||
|
}
|
||||||
|
|
||||||
mut middlewares := s.app.context_middlewares.clone()
|
mut middlewares := s.app.context_middlewares.clone()
|
||||||
|
|
||||||
// 按前缀长度排序,确保更具体的前缀后执行
|
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
|
||||||
mut prefixes := s.app.route_middlewares.keys()
|
for prefix in s.app.sorted_middleware_prefixes {
|
||||||
prefixes.sort(a.len < b.len)
|
|
||||||
|
|
||||||
for prefix in prefixes {
|
|
||||||
if path.starts_with(prefix) || prefix == '/' {
|
if path.starts_with(prefix) || prefix == '/' {
|
||||||
if mws := s.app.route_middlewares[prefix] {
|
if mws := s.app.route_middlewares[prefix] {
|
||||||
middlewares << mws
|
middlewares << mws
|
||||||
@@ -342,6 +374,9 @@ pub fn (mut app Hono) listen(port string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 优化:预计算中间件前缀排序
|
||||||
|
app.precompute_middleware_prefixes()
|
||||||
|
|
||||||
// 使用优化配置的 picoev 高性能服务器(支持高并发)
|
// 使用优化配置的 picoev 高性能服务器(支持高并发)
|
||||||
app.listen_picoev_with_config(PicoevConfig{
|
app.listen_picoev_with_config(PicoevConfig{
|
||||||
port: port_num
|
port: port_num
|
||||||
@@ -372,6 +407,7 @@ pub fn (mut app Hono) route(prefix string, mut subapp Hono) {
|
|||||||
} else {
|
} else {
|
||||||
app.route_middlewares[prefix] = subapp.context_middlewares.clone()
|
app.route_middlewares[prefix] = subapp.context_middlewares.clone()
|
||||||
}
|
}
|
||||||
|
app.has_middlewares = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// 继承子应用的 notFound 和 onError 处理器(如果主应用没有设置)
|
// 继承子应用的 notFound 和 onError 处理器(如果主应用没有设置)
|
||||||
@@ -508,5 +544,48 @@ pub fn Hono.new() Hono {
|
|||||||
fast_router: FastRouter.new()
|
fast_router: FastRouter.new()
|
||||||
use_fast_router: true
|
use_fast_router: true
|
||||||
route_middlewares: map[string][]ContextMiddleware{}
|
route_middlewares: map[string][]ContextMiddleware{}
|
||||||
|
sorted_middleware_prefixes: []string{}
|
||||||
|
has_middlewares: false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 快速解析 query string(单次遍历,避免 split)- app.v 版本
|
||||||
|
@[inline]
|
||||||
|
fn parse_query_string_app(query_str string) map[string]string {
|
||||||
|
mut query_map := map[string]string{}
|
||||||
|
len := query_str.len
|
||||||
|
|
||||||
|
if len == 0 {
|
||||||
|
return query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
mut key_start := 0
|
||||||
|
mut key_end := -1
|
||||||
|
mut value_start := -1
|
||||||
|
|
||||||
|
for i := 0; i <= len; i++ {
|
||||||
|
ch := if i < len { query_str[i] } else { `&` } // 末尾视为分隔符
|
||||||
|
|
||||||
|
if ch == `=` && key_end == -1 {
|
||||||
|
key_end = i
|
||||||
|
value_start = i + 1
|
||||||
|
} else if ch == `&` {
|
||||||
|
// 完成一个键值对
|
||||||
|
if key_end > key_start && value_start > 0 {
|
||||||
|
key := query_str[key_start..key_end]
|
||||||
|
value := if value_start < i { query_str[value_start..i] } else { '' }
|
||||||
|
query_map[key] = value
|
||||||
|
} else if key_end == -1 && i > key_start {
|
||||||
|
// 只有 key 没有 value
|
||||||
|
key := query_str[key_start..i]
|
||||||
|
query_map[key] = ''
|
||||||
|
}
|
||||||
|
// 重置状态
|
||||||
|
key_start = i + 1
|
||||||
|
key_end = -1
|
||||||
|
value_start = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return query_map
|
||||||
|
}
|
||||||
|
|||||||
+10
-18
@@ -2,27 +2,19 @@
|
|||||||
|
|
||||||
Performance benchmarks for V-Hono web framework.
|
Performance benchmarks for V-Hono web framework.
|
||||||
|
|
||||||
## Backend Comparison
|
## Framework Comparison (500 connections, 100K requests)
|
||||||
|
|
||||||
### uSockets vs Picoev (200 connections, 100K requests)
|
| Framework | RPS | Errors | Avg Latency | P50 | P95 | P99 |
|
||||||
|
|-----------|-----|--------|-------------|-----|-----|-----|
|
||||||
|
| **v-hono (uSockets)** | **20,231** | **0** | **24.62ms** | **23.65ms** | **33.82ms** | **57.29ms** |
|
||||||
|
| v-hono (picoev) | 16,177 | 0 | 30.75ms | 26.25ms | 35.37ms | 111.38ms |
|
||||||
|
| veb (V官方) | 7,278 | 772 | 68.06ms | 55.79ms | 71.62ms | 98.90ms |
|
||||||
|
|
||||||
| Backend | RPS | Avg Latency | P95 | P99 |
|
### Performance Summary
|
||||||
|---------|-----|-------------|-----|-----|
|
|
||||||
| uSockets | ~22,000 | 8.75ms | 16.66ms | 25.73ms |
|
|
||||||
| picoev | ~15,000 | 13.36ms | 18.89ms | 31.66ms |
|
|
||||||
|
|
||||||
**uSockets provides ~50% higher throughput under high concurrency.**
|
- **v-hono (uSockets) vs veb**: **2.78x faster**, zero errors
|
||||||
|
- **v-hono (uSockets) vs picoev**: **25% faster**, better P99 latency
|
||||||
### High Concurrency Test (500 connections, 100K requests)
|
- **v-hono (picoev) vs veb**: **2.22x faster**, zero errors
|
||||||
|
|
||||||
| Metric | uSockets |
|
|
||||||
|--------|----------|
|
|
||||||
| RPS | ~20,000 |
|
|
||||||
| Errors | 0 |
|
|
||||||
| Avg Latency | 25.04ms |
|
|
||||||
| P50 | 24.32ms |
|
|
||||||
| P95 | 32.97ms |
|
|
||||||
| P99 | 64.59ms |
|
|
||||||
|
|
||||||
## Running Benchmarks
|
## Running Benchmarks
|
||||||
|
|
||||||
|
|||||||
+6
-6
@@ -171,17 +171,18 @@ fn (router FastRouter) precompile_route(method string, handler IHandler) !Precom
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 快速路由匹配(优化版:静态路由跳过缓存 + 预分配结果)
|
// 快速路由匹配(优化版:静态路由跳过缓存 + 预分配结果 + 复用 cache key)
|
||||||
pub fn (mut router FastRouter) match_route(method string, path string) ?ContextRouteMatch {
|
pub fn (mut router FastRouter) match_route(method string, path string) ?ContextRouteMatch {
|
||||||
|
// 优化:只拼接一次 cache key,复用于静态路由和缓存查找
|
||||||
|
cache_key := '${method}:${path}'
|
||||||
|
|
||||||
// 1. 静态路由直接返回预分配的结果(零分配)
|
// 1. 静态路由直接返回预分配的结果(零分配)
|
||||||
static_key := '${method}:${path}'
|
if result := router.static_route_results[cache_key] {
|
||||||
if result := router.static_route_results[static_key] {
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 动态路由先检查 LRU 缓存(避免重复正则匹配)
|
// 2. 动态路由先检查 LRU 缓存(避免重复正则匹配)
|
||||||
if router.cache_enabled {
|
if router.cache_enabled {
|
||||||
cache_key := '${method}:${path}'
|
|
||||||
if cached := router.lru_cache.get(cache_key) {
|
if cached := router.lru_cache.get(cache_key) {
|
||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
@@ -208,9 +209,8 @@ pub fn (mut router FastRouter) match_route(method string, path string) ?ContextR
|
|||||||
base_path: ''
|
base_path: ''
|
||||||
}
|
}
|
||||||
|
|
||||||
// 只缓存动态路由结果
|
// 只缓存动态路由结果(复用 cache_key)
|
||||||
if router.cache_enabled {
|
if router.cache_enabled {
|
||||||
cache_key := '${method}:${path}'
|
|
||||||
router.lru_cache.put(cache_key, result)
|
router.lru_cache.put(cache_key, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+199
-45
@@ -79,7 +79,15 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
|
|||||||
if ctx.app.use_fast_router {
|
if ctx.app.use_fast_router {
|
||||||
if route_match := ctx.app.fast_router.match_route(method_str, path) {
|
if route_match := ctx.app.fast_router.match_route(method_str, path) {
|
||||||
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
|
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
|
||||||
middlewares := get_middlewares_for_path_picoev(ctx.app, path)
|
|
||||||
|
// 优化:零中间件快速路径
|
||||||
|
if !ctx.app.has_middlewares {
|
||||||
|
response := route_match.handler.handle(mut hono_ctx)
|
||||||
|
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
middlewares := get_middlewares_for_path_picoev_optimized(ctx.app, path)
|
||||||
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
|
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
|
||||||
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
||||||
return
|
return
|
||||||
@@ -89,7 +97,15 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
|
|||||||
// 回退到混合路由器
|
// 回退到混合路由器
|
||||||
if route_match := ctx.app.context_hybrid_router.match_route(method_str, path) {
|
if route_match := ctx.app.context_hybrid_router.match_route(method_str, path) {
|
||||||
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
|
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
|
||||||
middlewares := get_middlewares_for_path_picoev(ctx.app, path)
|
|
||||||
|
// 优化:零中间件快速路径
|
||||||
|
if !ctx.app.has_middlewares {
|
||||||
|
response := route_match.handler.handle(mut hono_ctx)
|
||||||
|
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
middlewares := get_middlewares_for_path_picoev_optimized(ctx.app, path)
|
||||||
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
|
response := exec_middlewares_picoev(0, middlewares, mut hono_ctx, route_match.handler)
|
||||||
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
|
||||||
return
|
return
|
||||||
@@ -118,25 +134,76 @@ fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picoht
|
|||||||
res.end()
|
res.end()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查客户端是否请求 Keep-Alive
|
// 检查客户端是否请求 Keep-Alive - 优化版
|
||||||
|
// 避免 to_lower() 创建新字符串,使用大小写不敏感比较
|
||||||
fn check_keepalive_request(req picohttpparser.Request) bool {
|
fn check_keepalive_request(req picohttpparser.Request) bool {
|
||||||
for i in 0 .. req.num_headers {
|
for i in 0 .. req.num_headers {
|
||||||
h := req.headers[i]
|
h := req.headers[i]
|
||||||
if h.name.to_lower() == 'connection' {
|
// 大小写不敏感比较 "connection"
|
||||||
return h.value.to_lower().contains('keep-alive')
|
if h.name.len == 10 && eq_ignore_case(h.name, 'connection') {
|
||||||
|
// 检查是否包含 "keep-alive"(大小写不敏感)
|
||||||
|
return contains_ignore_case(h.value, 'keep-alive')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true // HTTP/1.1 默认 Keep-Alive
|
return true // HTTP/1.1 默认 Keep-Alive
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取路径对应的所有中间件
|
// 大小写不敏感字符串比较(避免分配)
|
||||||
fn get_middlewares_for_path_picoev(app &Hono, path string) []ContextMiddleware {
|
@[inline]
|
||||||
|
fn eq_ignore_case(a string, b string) bool {
|
||||||
|
if a.len != b.len {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i in 0 .. a.len {
|
||||||
|
ca := a[i]
|
||||||
|
cb := b[i]
|
||||||
|
// 转换为小写比较
|
||||||
|
la := if ca >= `A` && ca <= `Z` { ca + 32 } else { ca }
|
||||||
|
lb := if cb >= `A` && cb <= `Z` { cb + 32 } else { cb }
|
||||||
|
if la != lb {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 大小写不敏感的 contains 检查(避免分配)
|
||||||
|
@[inline]
|
||||||
|
fn contains_ignore_case(haystack string, needle string) bool {
|
||||||
|
if needle.len > haystack.len {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
max_start := haystack.len - needle.len
|
||||||
|
for i := 0; i <= max_start; i++ {
|
||||||
|
mut found := true
|
||||||
|
for j in 0 .. needle.len {
|
||||||
|
ch := haystack[i + j]
|
||||||
|
cn := needle[j]
|
||||||
|
lh := if ch >= `A` && ch <= `Z` { ch + 32 } else { ch }
|
||||||
|
ln := if cn >= `A` && cn <= `Z` { cn + 32 } else { cn }
|
||||||
|
if lh != ln {
|
||||||
|
found = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取路径对应的所有中间件(优化版:使用预排序的前缀列表)
|
||||||
|
fn get_middlewares_for_path_picoev_optimized(app &Hono, path string) []ContextMiddleware {
|
||||||
|
// 优化:只有全局中间件时,直接返回引用(避免克隆)
|
||||||
|
if app.route_middlewares.len == 0 {
|
||||||
|
return app.context_middlewares
|
||||||
|
}
|
||||||
|
|
||||||
mut middlewares := app.context_middlewares.clone()
|
mut middlewares := app.context_middlewares.clone()
|
||||||
|
|
||||||
mut prefixes := app.route_middlewares.keys()
|
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
|
||||||
prefixes.sort(a.len < b.len)
|
for prefix in app.sorted_middleware_prefixes {
|
||||||
|
|
||||||
for prefix in prefixes {
|
|
||||||
if path.starts_with(prefix) || prefix == '/' {
|
if path.starts_with(prefix) || prefix == '/' {
|
||||||
if mws := app.route_middlewares[prefix] {
|
if mws := app.route_middlewares[prefix] {
|
||||||
middlewares << mws
|
middlewares << mws
|
||||||
@@ -147,6 +214,11 @@ fn get_middlewares_for_path_picoev(app &Hono, path string) []ContextMiddleware {
|
|||||||
return middlewares
|
return middlewares
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 获取路径对应的所有中间件(保留旧版本兼容)
|
||||||
|
fn get_middlewares_for_path_picoev(app &Hono, path string) []ContextMiddleware {
|
||||||
|
return get_middlewares_for_path_picoev_optimized(app, path)
|
||||||
|
}
|
||||||
|
|
||||||
// 执行中间件链
|
// 执行中间件链
|
||||||
fn exec_middlewares_picoev(idx int, middlewares []ContextMiddleware, mut ctx Context, handler IHandler) http.Response {
|
fn exec_middlewares_picoev(idx int, middlewares []ContextMiddleware, mut ctx Context, handler IHandler) http.Response {
|
||||||
if idx < middlewares.len {
|
if idx < middlewares.len {
|
||||||
@@ -158,40 +230,96 @@ fn exec_middlewares_picoev(idx int, middlewares []ContextMiddleware, mut ctx Con
|
|||||||
return handler.handle(mut ctx)
|
return handler.handle(mut ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析路径和查询参数
|
// 解析路径和查询参数 - 零分配优化版
|
||||||
|
// 使用指针遍历避免创建临时数组
|
||||||
fn parse_path_and_query(full_path string) (string, map[string]string) {
|
fn parse_path_and_query(full_path string) (string, map[string]string) {
|
||||||
mut query_map := map[string]string{}
|
mut query_map := map[string]string{}
|
||||||
|
len := full_path.len
|
||||||
|
|
||||||
if idx := full_path.index('?') {
|
if len == 0 {
|
||||||
path := full_path[..idx]
|
|
||||||
query_str := full_path[idx + 1..]
|
|
||||||
|
|
||||||
for part in query_str.split('&') {
|
|
||||||
if eq_idx := part.index('=') {
|
|
||||||
query_map[part[..eq_idx]] = part[eq_idx + 1..]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return path, query_map
|
|
||||||
}
|
|
||||||
|
|
||||||
return full_path, query_map
|
return full_path, query_map
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建 picoev 上下文
|
// 快速路径:大多数请求没有查询参数
|
||||||
|
// 从后向前搜索 '?' 通常更快(查询参数在末尾)
|
||||||
|
mut query_start := -1
|
||||||
|
for i := len - 1; i >= 0; i-- {
|
||||||
|
if full_path[i] == `?` {
|
||||||
|
query_start = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 没有查询参数,直接返回(最常见情况)
|
||||||
|
if query_start == -1 {
|
||||||
|
return full_path, query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
path := full_path[..query_start]
|
||||||
|
|
||||||
|
// 解析查询参数(单次遍历,避免 split)
|
||||||
|
mut key_start := query_start + 1
|
||||||
|
mut key_end := -1
|
||||||
|
mut value_start := -1
|
||||||
|
|
||||||
|
for i := query_start + 1; i <= len; i++ {
|
||||||
|
ch := if i < len { full_path[i] } else { `&` } // 末尾视为分隔符
|
||||||
|
|
||||||
|
if ch == `=` && key_end == -1 {
|
||||||
|
key_end = i
|
||||||
|
value_start = i + 1
|
||||||
|
} else if ch == `&` {
|
||||||
|
// 完成一个键值对
|
||||||
|
if key_end > key_start && value_start > 0 {
|
||||||
|
key := full_path[key_start..key_end]
|
||||||
|
value := if value_start < i { full_path[value_start..i] } else { '' }
|
||||||
|
query_map[key] = value
|
||||||
|
} else if key_end == -1 && i > key_start {
|
||||||
|
// 只有 key 没有 value(如 ?foo&bar=1)
|
||||||
|
key := full_path[key_start..i]
|
||||||
|
query_map[key] = ''
|
||||||
|
}
|
||||||
|
// 重置状态
|
||||||
|
key_start = i + 1
|
||||||
|
key_end = -1
|
||||||
|
value_start = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return path, query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建 picoev 上下文 - 优化版
|
||||||
|
// 延迟转换 http.Request,只在真正需要时才转换
|
||||||
fn create_picoev_context(req picohttpparser.Request, params map[string]string, query map[string]string) Context {
|
fn create_picoev_context(req picohttpparser.Request, params map[string]string, query map[string]string) Context {
|
||||||
|
// 提取纯路径(不含查询参数)
|
||||||
|
path := extract_path_only(req.path)
|
||||||
|
|
||||||
return Context{
|
return Context{
|
||||||
req: convert_picoev_request(req)
|
req: convert_picoev_request(req)
|
||||||
params: params
|
params: params
|
||||||
query: query
|
query: query
|
||||||
body: req.body
|
body: req.body
|
||||||
url: req.path
|
url: req.path
|
||||||
path: req.path
|
path: path
|
||||||
status_code: 200
|
status_code: 200
|
||||||
headers: map[string]string{}
|
headers: map[string]string{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 转换 picoev 请求
|
// 快速提取路径(不含查询参数)
|
||||||
|
@[inline]
|
||||||
|
fn extract_path_only(full_path string) string {
|
||||||
|
for i in 0 .. full_path.len {
|
||||||
|
if full_path[i] == `?` {
|
||||||
|
return full_path[..i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return full_path
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转换 picoev 请求 - 优化版
|
||||||
|
// 使用预计算的方法映射避免字符串比较
|
||||||
fn convert_picoev_request(req picohttpparser.Request) http.Request {
|
fn convert_picoev_request(req picohttpparser.Request) http.Request {
|
||||||
mut headers := http.new_header()
|
mut headers := http.new_header()
|
||||||
|
|
||||||
@@ -201,23 +329,46 @@ fn convert_picoev_request(req picohttpparser.Request) http.Request {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return http.Request{
|
return http.Request{
|
||||||
method: match req.method {
|
method: parse_http_method_fast(req.method)
|
||||||
'GET' { http.Method.get }
|
|
||||||
'POST' { http.Method.post }
|
|
||||||
'PUT' { http.Method.put }
|
|
||||||
'DELETE' { http.Method.delete }
|
|
||||||
'PATCH' { http.Method.patch }
|
|
||||||
'HEAD' { http.Method.head }
|
|
||||||
'OPTIONS' { http.Method.options }
|
|
||||||
else { http.Method.get }
|
|
||||||
}
|
|
||||||
url: req.path
|
url: req.path
|
||||||
data: req.body
|
data: req.body
|
||||||
header: headers
|
header: headers
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送 picoev 响应
|
// 快速 HTTP 方法解析(基于首字符和长度)
|
||||||
|
@[inline]
|
||||||
|
fn parse_http_method_fast(method string) http.Method {
|
||||||
|
len := method.len
|
||||||
|
if len == 0 {
|
||||||
|
return http.Method.get
|
||||||
|
}
|
||||||
|
|
||||||
|
// 基于首字符快速分支
|
||||||
|
match method[0] {
|
||||||
|
`G` {
|
||||||
|
if len == 3 { return http.Method.get }
|
||||||
|
}
|
||||||
|
`P` {
|
||||||
|
if len == 4 && method[1] == `O` { return http.Method.post }
|
||||||
|
if len == 3 && method[1] == `U` { return http.Method.put }
|
||||||
|
if len == 5 { return http.Method.patch }
|
||||||
|
}
|
||||||
|
`D` {
|
||||||
|
if len == 6 { return http.Method.delete }
|
||||||
|
}
|
||||||
|
`H` {
|
||||||
|
if len == 4 { return http.Method.head }
|
||||||
|
}
|
||||||
|
`O` {
|
||||||
|
if len == 7 { return http.Method.options }
|
||||||
|
}
|
||||||
|
else {}
|
||||||
|
}
|
||||||
|
return http.Method.get
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送 picoev 响应 - 优化版
|
||||||
fn send_picoev_response(mut res picohttpparser.Response, ctx Context, response http.Response, keepalive bool, config PicoevConfig) {
|
fn send_picoev_response(mut res picohttpparser.Response, ctx Context, response http.Response, keepalive bool, config PicoevConfig) {
|
||||||
status_code := if ctx.status_code != 0 { ctx.status_code } else { response.status_code }
|
status_code := if ctx.status_code != 0 { ctx.status_code } else { response.status_code }
|
||||||
|
|
||||||
@@ -231,18 +382,21 @@ fn send_picoev_response(mut res picohttpparser.Response, ctx Context, response h
|
|||||||
mut has_connection := false
|
mut has_connection := false
|
||||||
|
|
||||||
for key, value in ctx.headers {
|
for key, value in ctx.headers {
|
||||||
// 跳过 Content-Length,picohttpparser 会在 body() 时自动添加
|
// 使用快速大小写不敏感比较
|
||||||
if key.to_lower() == 'content-length' {
|
key_len := key.len
|
||||||
continue
|
if key_len == 14 && eq_ignore_case(key, 'content-length') {
|
||||||
|
continue // 跳过 Content-Length
|
||||||
}
|
}
|
||||||
res.header(key, value)
|
res.header(key, value)
|
||||||
key_lower := key.to_lower()
|
if key_len == 12 && eq_ignore_case(key, 'content-type') {
|
||||||
if key_lower == 'content-type' { has_content_type = true }
|
has_content_type = true
|
||||||
if key_lower == 'connection' { has_connection = true }
|
} else if key_len == 10 && eq_ignore_case(key, 'connection') {
|
||||||
|
has_connection = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if content_type := response.header.get(.content_type) {
|
|
||||||
if !has_content_type {
|
if !has_content_type {
|
||||||
|
if content_type := response.header.get(.content_type) {
|
||||||
res.header('Content-Type', content_type)
|
res.header('Content-Type', content_type)
|
||||||
has_content_type = true
|
has_content_type = true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -208,10 +208,34 @@ pub fn (router ContextHybridRouter) match_static_route(method string, path strin
|
|||||||
return none
|
return none
|
||||||
}
|
}
|
||||||
|
|
||||||
// Context 版本的动态路径匹配
|
// Context 版本的动态路径匹配(保留旧版本兼容)
|
||||||
fn (mut router ContextHybridRouter) match_dynamic_route(method string, path string) ?ContextRouteMatch {
|
fn (mut router ContextHybridRouter) match_dynamic_route(method string, path string) ?ContextRouteMatch {
|
||||||
// 先检查缓存
|
|
||||||
cache_key := '${method}:${path}'
|
cache_key := '${method}:${path}'
|
||||||
|
return router.match_dynamic_route_with_key(cache_key, method, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Context 版本的主匹配函数(优化版:复用 cache key)
|
||||||
|
pub fn (mut router ContextHybridRouter) match_route(method string, path string) ?ContextRouteMatch {
|
||||||
|
// 优化:只拼接一次 cache key
|
||||||
|
cache_key := '${method}:${path}'
|
||||||
|
|
||||||
|
// 1. 先尝试静态路径匹配(最快)
|
||||||
|
if cache_key in router.static_routes {
|
||||||
|
return ContextRouteMatch{
|
||||||
|
handler: router.static_routes[cache_key]
|
||||||
|
params: map[string]string{}
|
||||||
|
path: path
|
||||||
|
base_path: ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 再尝试动态路径匹配(复用 cache_key)
|
||||||
|
return router.match_dynamic_route_with_key(cache_key, method, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Context 版本的动态路径匹配(优化版:接收预计算的 cache_key)
|
||||||
|
fn (mut router ContextHybridRouter) match_dynamic_route_with_key(cache_key string, method string, path string) ?ContextRouteMatch {
|
||||||
|
// 先检查缓存
|
||||||
if cached := router.cache.get(cache_key) {
|
if cached := router.cache.get(cache_key) {
|
||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
@@ -240,22 +264,6 @@ fn (mut router ContextHybridRouter) match_dynamic_route(method string, path stri
|
|||||||
return none
|
return none
|
||||||
}
|
}
|
||||||
|
|
||||||
// Context 版本的主匹配函数
|
|
||||||
pub fn (mut router ContextHybridRouter) match_route(method string, path string) ?ContextRouteMatch {
|
|
||||||
// 1. 先尝试静态路径匹配(最快)
|
|
||||||
if static_handler := router.match_static_route(method, path) {
|
|
||||||
return ContextRouteMatch{
|
|
||||||
handler: static_handler
|
|
||||||
params: map[string]string{}
|
|
||||||
path: path
|
|
||||||
base_path: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 再尝试动态路径匹配
|
|
||||||
return router.match_dynamic_route(method, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Context 版本的获取所有路由
|
// Context 版本的获取所有路由
|
||||||
pub fn (router ContextHybridRouter) get_all_routes() ([]string, []string) {
|
pub fn (router ContextHybridRouter) get_all_routes() ([]string, []string) {
|
||||||
mut static_paths := []string{}
|
mut static_paths := []string{}
|
||||||
|
|||||||
@@ -0,0 +1,282 @@
|
|||||||
|
module main
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
// 测试 HTTP 解析优化
|
||||||
|
|
||||||
|
// 原始版本 - 使用 split 和 index
|
||||||
|
fn parse_path_and_query_original(full_path string) (string, map[string]string) {
|
||||||
|
mut query_map := map[string]string{}
|
||||||
|
|
||||||
|
if idx := full_path.index('?') {
|
||||||
|
path := full_path[..idx]
|
||||||
|
query_str := full_path[idx + 1..]
|
||||||
|
|
||||||
|
for part in query_str.split('&') {
|
||||||
|
if eq_idx := part.index('=') {
|
||||||
|
query_map[part[..eq_idx]] = part[eq_idx + 1..]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return path, query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
return full_path, query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
// 优化版本 - 零分配单次遍历
|
||||||
|
fn parse_path_and_query_optimized(full_path string) (string, map[string]string) {
|
||||||
|
mut query_map := map[string]string{}
|
||||||
|
len := full_path.len
|
||||||
|
|
||||||
|
if len == 0 {
|
||||||
|
return full_path, query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 查找 '?' 位置(单次遍历)
|
||||||
|
mut query_start := -1
|
||||||
|
for i in 0 .. len {
|
||||||
|
if full_path[i] == `?` {
|
||||||
|
query_start = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 没有查询参数,直接返回
|
||||||
|
if query_start == -1 {
|
||||||
|
return full_path, query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
path := full_path[..query_start]
|
||||||
|
|
||||||
|
// 2. 解析查询参数(单次遍历,避免 split)
|
||||||
|
mut key_start := query_start + 1
|
||||||
|
mut key_end := -1
|
||||||
|
mut value_start := -1
|
||||||
|
|
||||||
|
for i := query_start + 1; i <= len; i++ {
|
||||||
|
ch := if i < len { full_path[i] } else { `&` } // 末尾视为分隔符
|
||||||
|
|
||||||
|
if ch == `=` && key_end == -1 {
|
||||||
|
key_end = i
|
||||||
|
value_start = i + 1
|
||||||
|
} else if ch == `&` {
|
||||||
|
// 完成一个键值对
|
||||||
|
if key_end > key_start && value_start > 0 {
|
||||||
|
key := full_path[key_start..key_end]
|
||||||
|
value := if value_start < i { full_path[value_start..i] } else { '' }
|
||||||
|
query_map[key] = value
|
||||||
|
} else if key_end == -1 && i > key_start {
|
||||||
|
// 只有 key 没有 value(如 ?foo&bar=1)
|
||||||
|
key := full_path[key_start..i]
|
||||||
|
query_map[key] = ''
|
||||||
|
}
|
||||||
|
// 重置状态
|
||||||
|
key_start = i + 1
|
||||||
|
key_end = -1
|
||||||
|
value_start = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return path, query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep-Alive 检查 - 原始版本
|
||||||
|
fn check_keepalive_original(name string, value string) bool {
|
||||||
|
return name.to_lower() == 'connection' && value.to_lower().contains('keep-alive')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 大小写不敏感比较
|
||||||
|
@[inline]
|
||||||
|
fn eq_ignore_case(a string, b string) bool {
|
||||||
|
if a.len != b.len {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i in 0 .. a.len {
|
||||||
|
ca := a[i]
|
||||||
|
cb := b[i]
|
||||||
|
la := if ca >= `A` && ca <= `Z` { ca + 32 } else { ca }
|
||||||
|
lb := if cb >= `A` && cb <= `Z` { cb + 32 } else { cb }
|
||||||
|
if la != lb {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 大小写不敏感 contains
|
||||||
|
@[inline]
|
||||||
|
fn contains_ignore_case(haystack string, needle string) bool {
|
||||||
|
if needle.len > haystack.len {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
max_start := haystack.len - needle.len
|
||||||
|
for i := 0; i <= max_start; i++ {
|
||||||
|
mut found := true
|
||||||
|
for j in 0 .. needle.len {
|
||||||
|
ch := haystack[i + j]
|
||||||
|
cn := needle[j]
|
||||||
|
lh := if ch >= `A` && ch <= `Z` { ch + 32 } else { ch }
|
||||||
|
ln := if cn >= `A` && cn <= `Z` { cn + 32 } else { cn }
|
||||||
|
if lh != ln {
|
||||||
|
found = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep-Alive 检查 - 优化版本
|
||||||
|
fn check_keepalive_optimized(name string, value string) bool {
|
||||||
|
return name.len == 10 && eq_ignore_case(name, 'connection') && contains_ignore_case(value, 'keep-alive')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试正确性
|
||||||
|
fn test_correctness() {
|
||||||
|
println('=== 测试正确性 ===')
|
||||||
|
|
||||||
|
test_cases := [
|
||||||
|
'/api/users',
|
||||||
|
'/api/users?id=123',
|
||||||
|
'/api/users?id=123&name=test',
|
||||||
|
'/api/users?id=123&name=test&active=true',
|
||||||
|
'/search?q=hello+world&page=1&limit=10',
|
||||||
|
'/path?empty=&key=value',
|
||||||
|
'/path?novalue&key=value',
|
||||||
|
'/',
|
||||||
|
'/?single=param',
|
||||||
|
]
|
||||||
|
|
||||||
|
mut all_passed := true
|
||||||
|
|
||||||
|
for tc in test_cases {
|
||||||
|
path_orig, query_orig := parse_path_and_query_original(tc)
|
||||||
|
path_opt, query_opt := parse_path_and_query_optimized(tc)
|
||||||
|
|
||||||
|
if path_orig != path_opt {
|
||||||
|
println('❌ 路径不匹配: ${tc}')
|
||||||
|
println(' 原始: ${path_orig}')
|
||||||
|
println(' 优化: ${path_opt}')
|
||||||
|
all_passed = false
|
||||||
|
} else if query_orig.len != query_opt.len {
|
||||||
|
println('❌ 查询参数数量不匹配: ${tc}')
|
||||||
|
println(' 原始: ${query_orig}')
|
||||||
|
println(' 优化: ${query_opt}')
|
||||||
|
all_passed = false
|
||||||
|
} else {
|
||||||
|
mut params_match := true
|
||||||
|
for k, v in query_orig {
|
||||||
|
if k !in query_opt || query_opt[k] != v {
|
||||||
|
params_match = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !params_match {
|
||||||
|
println('❌ 查询参数值不匹配: ${tc}')
|
||||||
|
println(' 原始: ${query_orig}')
|
||||||
|
println(' 优化: ${query_opt}')
|
||||||
|
all_passed = false
|
||||||
|
} else {
|
||||||
|
println('✓ ${tc}')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if all_passed {
|
||||||
|
println('\n✅ 所有正确性测试通过!')
|
||||||
|
} else {
|
||||||
|
println('\n❌ 部分测试失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 性能基准测试
|
||||||
|
fn benchmark_performance() {
|
||||||
|
println('\n=== 性能基准测试 ===')
|
||||||
|
|
||||||
|
// 测试用例
|
||||||
|
test_paths := [
|
||||||
|
'/api/users', // 无查询参数
|
||||||
|
'/api/users?id=123', // 单个参数
|
||||||
|
'/api/users?id=123&name=test&active=true', // 多个参数
|
||||||
|
'/search?q=hello+world&page=1&limit=10&sort=desc&filter=active', // 复杂查询
|
||||||
|
]
|
||||||
|
|
||||||
|
iterations := 100000
|
||||||
|
|
||||||
|
for test_path in test_paths {
|
||||||
|
// 原始版本
|
||||||
|
sw_orig := time.new_stopwatch()
|
||||||
|
for _ in 0 .. iterations {
|
||||||
|
_, _ := parse_path_and_query_original(test_path)
|
||||||
|
}
|
||||||
|
time_orig := sw_orig.elapsed().microseconds()
|
||||||
|
|
||||||
|
// 优化版本
|
||||||
|
sw_opt := time.new_stopwatch()
|
||||||
|
for _ in 0 .. iterations {
|
||||||
|
_, _ := parse_path_and_query_optimized(test_path)
|
||||||
|
}
|
||||||
|
time_opt := sw_opt.elapsed().microseconds()
|
||||||
|
|
||||||
|
speedup := f64(time_orig) / f64(time_opt)
|
||||||
|
|
||||||
|
println('\n路径: ${test_path}')
|
||||||
|
println(' 原始版本: ${time_orig} μs (${iterations} 次)')
|
||||||
|
println(' 优化版本: ${time_opt} μs (${iterations} 次)')
|
||||||
|
println(' 提升: ${speedup:.2f}x')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试 Keep-Alive 检查优化
|
||||||
|
fn test_keepalive_optimization() {
|
||||||
|
println('\n=== Keep-Alive 检查优化测试 ===')
|
||||||
|
|
||||||
|
test_cases := [
|
||||||
|
['Connection', 'keep-alive'],
|
||||||
|
['connection', 'Keep-Alive'],
|
||||||
|
['CONNECTION', 'KEEP-ALIVE'],
|
||||||
|
['Content-Type', 'application/json'],
|
||||||
|
['Connection', 'close'],
|
||||||
|
]
|
||||||
|
|
||||||
|
iterations := 100000
|
||||||
|
|
||||||
|
// 原始版本
|
||||||
|
sw_orig := time.new_stopwatch()
|
||||||
|
for _ in 0 .. iterations {
|
||||||
|
for tc in test_cases {
|
||||||
|
_ := check_keepalive_original(tc[0], tc[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
time_orig := sw_orig.elapsed().microseconds()
|
||||||
|
|
||||||
|
// 优化版本
|
||||||
|
sw_opt := time.new_stopwatch()
|
||||||
|
for _ in 0 .. iterations {
|
||||||
|
for tc in test_cases {
|
||||||
|
_ := check_keepalive_optimized(tc[0], tc[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
time_opt := sw_opt.elapsed().microseconds()
|
||||||
|
|
||||||
|
speedup := f64(time_orig) / f64(time_opt)
|
||||||
|
|
||||||
|
println('原始版本: ${time_orig} μs (${iterations * test_cases.len} 次检查)')
|
||||||
|
println('优化版本: ${time_opt} μs (${iterations * test_cases.len} 次检查)')
|
||||||
|
println('提升: ${speedup:.2f}x')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println('HTTP 解析优化测试')
|
||||||
|
println('=' .repeat(50))
|
||||||
|
|
||||||
|
test_correctness()
|
||||||
|
benchmark_performance()
|
||||||
|
test_keepalive_optimization()
|
||||||
|
|
||||||
|
println('\n' + '=' .repeat(50))
|
||||||
|
println('测试完成!')
|
||||||
|
}
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
// 中间件优化测试
|
||||||
|
// 测试三个优化点:
|
||||||
|
// 1. 零中间件快速路径
|
||||||
|
// 2. 中间件预计算(启动时排序)
|
||||||
|
// 3. 复用 cache key
|
||||||
|
|
||||||
|
import hono
|
||||||
|
import time
|
||||||
|
import net.http
|
||||||
|
|
||||||
|
// 测试统计
|
||||||
|
struct TestStats {
|
||||||
|
mut:
|
||||||
|
total_tests int
|
||||||
|
passed_tests int
|
||||||
|
failed_tests int
|
||||||
|
}
|
||||||
|
|
||||||
|
fn (mut stats TestStats) start_test(test_name string) {
|
||||||
|
stats.total_tests++
|
||||||
|
print('🧪 ${test_name}... ')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn (mut stats TestStats) pass_test() {
|
||||||
|
stats.passed_tests++
|
||||||
|
println('✅')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn (mut stats TestStats) fail_test(error string) {
|
||||||
|
stats.failed_tests++
|
||||||
|
println('❌ ${error}')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn (stats TestStats) print_summary() {
|
||||||
|
println('\n=== 测试总结 ===')
|
||||||
|
println('总测试数: ${stats.total_tests}')
|
||||||
|
println('通过: ${stats.passed_tests}')
|
||||||
|
println('失败: ${stats.failed_tests}')
|
||||||
|
if stats.failed_tests == 0 {
|
||||||
|
println('🎉 所有测试通过!')
|
||||||
|
} else {
|
||||||
|
println('⚠️ 有 ${stats.failed_tests} 个测试失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试1:零中间件快速路径 - has_middlewares 标志
|
||||||
|
fn test_zero_middleware_flag(mut stats TestStats) {
|
||||||
|
stats.start_test('零中间件标志 (has_middlewares)')
|
||||||
|
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
// 新创建的应用应该没有中间件
|
||||||
|
if app.has_middlewares {
|
||||||
|
stats.fail_test('新应用不应该有中间件标志')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加中间件后标志应该为 true
|
||||||
|
app.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
|
||||||
|
return next(mut c)
|
||||||
|
})
|
||||||
|
|
||||||
|
if !app.has_middlewares {
|
||||||
|
stats.fail_test('添加中间件后标志应该为 true')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
stats.pass_test()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试2:中间件预计算 - sorted_middleware_prefixes
|
||||||
|
fn test_middleware_precompute(mut stats TestStats) {
|
||||||
|
stats.start_test('中间件预计算 (sorted_middleware_prefixes)')
|
||||||
|
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
// 添加路由
|
||||||
|
app.get('/test', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('test')
|
||||||
|
})
|
||||||
|
|
||||||
|
// 创建子应用并添加中间件
|
||||||
|
mut sub_app := hono.Hono.new()
|
||||||
|
sub_app.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
|
||||||
|
return next(mut c)
|
||||||
|
})
|
||||||
|
sub_app.get('/hello', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('hello')
|
||||||
|
})
|
||||||
|
|
||||||
|
// 挂载子应用
|
||||||
|
app.route('/api', mut sub_app)
|
||||||
|
|
||||||
|
// 预计算前,sorted_middleware_prefixes 应该为空
|
||||||
|
if app.sorted_middleware_prefixes.len != 0 {
|
||||||
|
stats.fail_test('预计算前 sorted_middleware_prefixes 应该为空')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用预计算
|
||||||
|
app.precompute_middleware_prefixes()
|
||||||
|
|
||||||
|
// 预计算后,sorted_middleware_prefixes 应该包含前缀
|
||||||
|
if app.sorted_middleware_prefixes.len == 0 && app.route_middlewares.len > 0 {
|
||||||
|
stats.fail_test('预计算后 sorted_middleware_prefixes 应该包含前缀')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证 has_middlewares 标志
|
||||||
|
if app.route_middlewares.len > 0 && !app.has_middlewares {
|
||||||
|
stats.fail_test('有路由中间件时 has_middlewares 应该为 true')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
stats.pass_test()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试3:FastRouter cache key 复用
|
||||||
|
fn test_fast_router_cache_key_reuse(mut stats TestStats) {
|
||||||
|
stats.start_test('FastRouter cache key 复用')
|
||||||
|
|
||||||
|
mut router := hono.FastRouter.new()
|
||||||
|
|
||||||
|
// 添加静态路由
|
||||||
|
static_handler := hono.ContextHandler{
|
||||||
|
path: '/users'
|
||||||
|
handler: fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('users')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
router.add_route('GET', static_handler, '') or {
|
||||||
|
stats.fail_test('添加静态路由失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加动态路由
|
||||||
|
dynamic_handler := hono.ContextHandler{
|
||||||
|
path: '/users/:id'
|
||||||
|
handler: fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('user')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
router.add_route('GET', dynamic_handler, '') or {
|
||||||
|
stats.fail_test('添加动态路由失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试静态路由匹配
|
||||||
|
if _ := router.match_route('GET', '/users') {
|
||||||
|
// 成功
|
||||||
|
} else {
|
||||||
|
stats.fail_test('静态路由匹配失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试动态路由匹配(第一次,会缓存)
|
||||||
|
if match1 := router.match_route('GET', '/users/123') {
|
||||||
|
if match1.params['id'] != '123' {
|
||||||
|
stats.fail_test('参数提取失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stats.fail_test('动态路由匹配失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试动态路由匹配(第二次,应该命中缓存)
|
||||||
|
if match2 := router.match_route('GET', '/users/123') {
|
||||||
|
if match2.params['id'] != '123' {
|
||||||
|
stats.fail_test('缓存命中后参数提取失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stats.fail_test('缓存命中失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证缓存状态
|
||||||
|
_, _, cache_count := router.get_stats()
|
||||||
|
if cache_count == 0 {
|
||||||
|
stats.fail_test('缓存应该有条目')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
stats.pass_test()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试4:HybridRouter cache key 复用
|
||||||
|
fn test_hybrid_router_cache_key_reuse(mut stats TestStats) {
|
||||||
|
stats.start_test('HybridRouter cache key 复用')
|
||||||
|
|
||||||
|
mut router := hono.ContextHybridRouter.new()
|
||||||
|
|
||||||
|
// 添加动态路由
|
||||||
|
dynamic_handler := hono.ContextHandler{
|
||||||
|
path: '/posts/:id'
|
||||||
|
handler: fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('post')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
router.add_route('GET', dynamic_handler, '')
|
||||||
|
|
||||||
|
// 第一次匹配(无缓存)
|
||||||
|
if match1 := router.match_route('GET', '/posts/456') {
|
||||||
|
if match1.params['id'] != '456' {
|
||||||
|
stats.fail_test('参数提取失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stats.fail_test('动态路由匹配失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 第二次匹配(应该命中缓存)
|
||||||
|
if match2 := router.match_route('GET', '/posts/456') {
|
||||||
|
if match2.params['id'] != '456' {
|
||||||
|
stats.fail_test('缓存命中后参数提取失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stats.fail_test('缓存命中失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
stats.pass_test()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试5:性能对比 - 有中间件 vs 无中间件
|
||||||
|
fn test_middleware_performance_comparison(mut stats TestStats) {
|
||||||
|
stats.start_test('中间件性能对比')
|
||||||
|
|
||||||
|
// 创建无中间件的路由器
|
||||||
|
mut router_no_mw := hono.FastRouter.new()
|
||||||
|
handler := hono.ContextHandler{
|
||||||
|
path: '/api/users/:id'
|
||||||
|
handler: fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('user')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
router_no_mw.add_route('GET', handler, '') or {
|
||||||
|
stats.fail_test('添加路由失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 预热
|
||||||
|
for _ in 0 .. 100 {
|
||||||
|
_ := router_no_mw.match_route('GET', '/api/users/123') or { continue }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试无中间件性能
|
||||||
|
iterations := 10000
|
||||||
|
start_no_mw := time.now()
|
||||||
|
for _ in 0 .. iterations {
|
||||||
|
_ := router_no_mw.match_route('GET', '/api/users/123') or { continue }
|
||||||
|
}
|
||||||
|
duration_no_mw := time.since(start_no_mw)
|
||||||
|
|
||||||
|
// 创建有中间件的应用
|
||||||
|
mut app_with_mw := hono.Hono.new()
|
||||||
|
app_with_mw.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
|
||||||
|
return next(mut c)
|
||||||
|
})
|
||||||
|
app_with_mw.get('/api/users/:id', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('user')
|
||||||
|
})
|
||||||
|
app_with_mw.precompute_middleware_prefixes()
|
||||||
|
|
||||||
|
// 预热
|
||||||
|
for _ in 0 .. 100 {
|
||||||
|
_ := app_with_mw.fast_router.match_route('GET', '/api/users/123') or { continue }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试有中间件性能
|
||||||
|
start_with_mw := time.now()
|
||||||
|
for _ in 0 .. iterations {
|
||||||
|
_ := app_with_mw.fast_router.match_route('GET', '/api/users/123') or { continue }
|
||||||
|
}
|
||||||
|
duration_with_mw := time.since(start_with_mw)
|
||||||
|
|
||||||
|
println('')
|
||||||
|
println(' 📊 无中间件: ${duration_no_mw.milliseconds()}ms (${iterations} 次)')
|
||||||
|
println(' 📊 有中间件: ${duration_with_mw.milliseconds()}ms (${iterations} 次)')
|
||||||
|
|
||||||
|
// 性能差异不应该太大(路由匹配本身不受中间件影响)
|
||||||
|
stats.pass_test()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试6:预计算排序正确性
|
||||||
|
fn test_precompute_sorting(mut stats TestStats) {
|
||||||
|
stats.start_test('预计算排序正确性')
|
||||||
|
|
||||||
|
mut app := hono.Hono.new()
|
||||||
|
|
||||||
|
// 添加多个子应用,模拟不同长度的前缀
|
||||||
|
mut sub1 := hono.Hono.new()
|
||||||
|
sub1.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
|
||||||
|
return next(mut c)
|
||||||
|
})
|
||||||
|
sub1.get('/test', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('test')
|
||||||
|
})
|
||||||
|
|
||||||
|
mut sub2 := hono.Hono.new()
|
||||||
|
sub2.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
|
||||||
|
return next(mut c)
|
||||||
|
})
|
||||||
|
sub2.get('/test', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('test')
|
||||||
|
})
|
||||||
|
|
||||||
|
mut sub3 := hono.Hono.new()
|
||||||
|
sub3.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
|
||||||
|
return next(mut c)
|
||||||
|
})
|
||||||
|
sub3.get('/test', fn (mut c hono.Context) http.Response {
|
||||||
|
return c.text('test')
|
||||||
|
})
|
||||||
|
|
||||||
|
// 按不同顺序挂载(长前缀先挂载)
|
||||||
|
app.route('/api/v1/users', mut sub1)
|
||||||
|
app.route('/api', mut sub2)
|
||||||
|
app.route('/api/v1', mut sub3)
|
||||||
|
|
||||||
|
// 预计算
|
||||||
|
app.precompute_middleware_prefixes()
|
||||||
|
|
||||||
|
// 验证排序:短前缀应该在前面
|
||||||
|
if app.sorted_middleware_prefixes.len >= 2 {
|
||||||
|
for i in 0 .. app.sorted_middleware_prefixes.len - 1 {
|
||||||
|
if app.sorted_middleware_prefixes[i].len > app.sorted_middleware_prefixes[i + 1].len {
|
||||||
|
stats.fail_test('前缀排序不正确:${app.sorted_middleware_prefixes[i]} 应该在 ${app.sorted_middleware_prefixes[i + 1]} 之后')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stats.pass_test()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println('🚀 开始中间件优化测试...\n')
|
||||||
|
|
||||||
|
mut stats := TestStats{}
|
||||||
|
|
||||||
|
// 运行所有测试
|
||||||
|
test_zero_middleware_flag(mut stats)
|
||||||
|
test_middleware_precompute(mut stats)
|
||||||
|
test_fast_router_cache_key_reuse(mut stats)
|
||||||
|
test_hybrid_router_cache_key_reuse(mut stats)
|
||||||
|
test_middleware_performance_comparison(mut stats)
|
||||||
|
test_precompute_sorting(mut stats)
|
||||||
|
|
||||||
|
// 打印测试总结
|
||||||
|
stats.print_summary()
|
||||||
|
}
|
||||||
+180
-40
@@ -49,6 +49,9 @@ pub fn (mut app Hono) listen_usockets(port int) {
|
|||||||
|
|
||||||
// 使用 uSockets 启动服务器(带配置)
|
// 使用 uSockets 启动服务器(带配置)
|
||||||
pub fn (mut app Hono) listen_usockets_with_config(config UsocketsConfig) {
|
pub fn (mut app Hono) listen_usockets_with_config(config UsocketsConfig) {
|
||||||
|
// 优化:预计算中间件前缀排序
|
||||||
|
app.precompute_middleware_prefixes()
|
||||||
|
|
||||||
// 存储到全局变量
|
// 存储到全局变量
|
||||||
g_usockets_app = unsafe { &app }
|
g_usockets_app = unsafe { &app }
|
||||||
g_usockets_config = config
|
g_usockets_config = config
|
||||||
@@ -102,9 +105,16 @@ fn usockets_on_data(s usockets.Socket, data &char, length int) usockets.Socket {
|
|||||||
if g_usockets_app.use_fast_router {
|
if g_usockets_app.use_fast_router {
|
||||||
if route_match := g_usockets_app.fast_router.match_route(method, path) {
|
if route_match := g_usockets_app.fast_router.match_route(method, path) {
|
||||||
mut hono_ctx := create_usockets_context(method, path, route_match.params, query_map, body)
|
mut hono_ctx := create_usockets_context(method, path, route_match.params, query_map, body)
|
||||||
middlewares := get_middlewares_for_path_usockets(g_usockets_app, path)
|
|
||||||
|
// 优化1:零中间件快速路径
|
||||||
|
if !g_usockets_app.has_middlewares {
|
||||||
|
response := route_match.handler.handle(mut hono_ctx)
|
||||||
|
send_usockets_response(s, hono_ctx, response)
|
||||||
|
} else {
|
||||||
|
middlewares := get_middlewares_for_path_usockets_optimized(g_usockets_app, path)
|
||||||
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
|
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
|
||||||
send_usockets_response(s, hono_ctx, response)
|
send_usockets_response(s, hono_ctx, response)
|
||||||
|
}
|
||||||
response_sent = true
|
response_sent = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,9 +123,16 @@ fn usockets_on_data(s usockets.Socket, data &char, length int) usockets.Socket {
|
|||||||
if !response_sent {
|
if !response_sent {
|
||||||
if route_match := g_usockets_app.context_hybrid_router.match_route(method, path) {
|
if route_match := g_usockets_app.context_hybrid_router.match_route(method, path) {
|
||||||
mut hono_ctx := create_usockets_context(method, path, route_match.params, query_map, body)
|
mut hono_ctx := create_usockets_context(method, path, route_match.params, query_map, body)
|
||||||
middlewares := get_middlewares_for_path_usockets(g_usockets_app, path)
|
|
||||||
|
// 优化1:零中间件快速路径
|
||||||
|
if !g_usockets_app.has_middlewares {
|
||||||
|
response := route_match.handler.handle(mut hono_ctx)
|
||||||
|
send_usockets_response(s, hono_ctx, response)
|
||||||
|
} else {
|
||||||
|
middlewares := get_middlewares_for_path_usockets_optimized(g_usockets_app, path)
|
||||||
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
|
response := exec_middlewares_usockets(0, middlewares, mut hono_ctx, route_match.handler)
|
||||||
send_usockets_response(s, hono_ctx, response)
|
send_usockets_response(s, hono_ctx, response)
|
||||||
|
}
|
||||||
response_sent = true
|
response_sent = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -152,57 +169,119 @@ fn usockets_on_end(s usockets.Socket) usockets.Socket {
|
|||||||
return s.close()
|
return s.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析 HTTP 请求
|
// 解析 HTTP 请求 - 零分配优化版
|
||||||
|
// 使用指针遍历避免创建临时数组
|
||||||
fn parse_http_request_usockets(raw string) (string, string, map[string]string, string) {
|
fn parse_http_request_usockets(raw string) (string, string, map[string]string, string) {
|
||||||
mut method := ''
|
mut method := ''
|
||||||
mut path := ''
|
mut path := ''
|
||||||
mut query_map := map[string]string{}
|
mut query_map := map[string]string{}
|
||||||
mut body := ''
|
mut body := ''
|
||||||
|
|
||||||
line_end := raw.index('\r\n') or { return method, path, query_map, body }
|
len := raw.len
|
||||||
request_line := raw[..line_end]
|
if len == 0 {
|
||||||
|
|
||||||
parts := request_line.split(' ')
|
|
||||||
if parts.len < 2 {
|
|
||||||
return method, path, query_map, body
|
return method, path, query_map, body
|
||||||
}
|
}
|
||||||
|
|
||||||
method = parts[0]
|
// 1. 查找第一行结束位置(\r\n)
|
||||||
full_path := parts[1]
|
mut line_end := -1
|
||||||
|
for i in 0 .. len - 1 {
|
||||||
|
if raw[i] == `\r` && raw[i + 1] == `\n` {
|
||||||
|
line_end = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if line_end == -1 {
|
||||||
|
return method, path, query_map, body
|
||||||
|
}
|
||||||
|
|
||||||
if query_idx := full_path.index('?') {
|
// 2. 解析 method(到第一个空格)
|
||||||
path = full_path[..query_idx]
|
mut method_end := 0
|
||||||
query_str := full_path[query_idx + 1..]
|
for method_end < line_end && raw[method_end] != ` ` {
|
||||||
for part in query_str.split('&') {
|
method_end++
|
||||||
if eq_idx := part.index('=') {
|
|
||||||
query_map[part[..eq_idx]] = part[eq_idx + 1..]
|
|
||||||
}
|
}
|
||||||
|
if method_end == 0 || method_end >= line_end {
|
||||||
|
return method, path, query_map, body
|
||||||
}
|
}
|
||||||
|
method = raw[..method_end]
|
||||||
|
|
||||||
|
// 3. 解析 path 和 query(从空格后到下一个空格)
|
||||||
|
mut path_start := method_end + 1
|
||||||
|
// 跳过多余空格
|
||||||
|
for path_start < line_end && raw[path_start] == ` ` {
|
||||||
|
path_start++
|
||||||
|
}
|
||||||
|
|
||||||
|
mut path_end := path_start
|
||||||
|
mut query_start := -1
|
||||||
|
for path_end < line_end && raw[path_end] != ` ` {
|
||||||
|
if raw[path_end] == `?` && query_start == -1 {
|
||||||
|
query_start = path_end + 1
|
||||||
|
}
|
||||||
|
path_end++
|
||||||
|
}
|
||||||
|
|
||||||
|
if query_start > 0 {
|
||||||
|
path = raw[path_start..query_start - 1]
|
||||||
|
// 解析 query string(单次遍历)
|
||||||
|
query_map = parse_query_string_fast(raw, query_start, path_end)
|
||||||
} else {
|
} else {
|
||||||
path = full_path
|
path = raw[path_start..path_end]
|
||||||
}
|
}
|
||||||
|
|
||||||
if body_start := raw.index('\r\n\r\n') {
|
// 4. 查找 body(\r\n\r\n 之后)
|
||||||
body = raw[body_start + 4..]
|
for i in line_end .. len - 3 {
|
||||||
|
if raw[i] == `\r` && raw[i + 1] == `\n` && raw[i + 2] == `\r` && raw[i + 3] == `\n` {
|
||||||
|
if i + 4 < len {
|
||||||
|
body = raw[i + 4..]
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return method, path, query_map, body
|
return method, path, query_map, body
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建 uSockets 上下文
|
// 快速解析 query string(单次遍历,避免 split)
|
||||||
|
@[inline]
|
||||||
|
fn parse_query_string_fast(raw string, start int, end int) map[string]string {
|
||||||
|
mut query_map := map[string]string{}
|
||||||
|
|
||||||
|
mut key_start := start
|
||||||
|
mut key_end := -1
|
||||||
|
mut value_start := -1
|
||||||
|
|
||||||
|
for i := start; i <= end; i++ {
|
||||||
|
ch := if i < end { raw[i] } else { `&` } // 末尾视为分隔符
|
||||||
|
|
||||||
|
if ch == `=` && key_end == -1 {
|
||||||
|
key_end = i
|
||||||
|
value_start = i + 1
|
||||||
|
} else if ch == `&` {
|
||||||
|
// 完成一个键值对
|
||||||
|
if key_end > key_start && value_start > 0 {
|
||||||
|
key := raw[key_start..key_end]
|
||||||
|
value := if value_start < i { raw[value_start..i] } else { '' }
|
||||||
|
query_map[key] = value
|
||||||
|
} else if key_end == -1 && i > key_start {
|
||||||
|
// 只有 key 没有 value
|
||||||
|
key := raw[key_start..i]
|
||||||
|
query_map[key] = ''
|
||||||
|
}
|
||||||
|
// 重置状态
|
||||||
|
key_start = i + 1
|
||||||
|
key_end = -1
|
||||||
|
value_start = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return query_map
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建 uSockets 上下文 - 优化版
|
||||||
fn create_usockets_context(method string, path string, params map[string]string, query map[string]string, body string) Context {
|
fn create_usockets_context(method string, path string, params map[string]string, query map[string]string, body string) Context {
|
||||||
return Context{
|
return Context{
|
||||||
req: http.Request{
|
req: http.Request{
|
||||||
method: match method {
|
method: parse_http_method_usockets(method)
|
||||||
'GET' { http.Method.get }
|
|
||||||
'POST' { http.Method.post }
|
|
||||||
'PUT' { http.Method.put }
|
|
||||||
'DELETE' { http.Method.delete }
|
|
||||||
'PATCH' { http.Method.patch }
|
|
||||||
'HEAD' { http.Method.head }
|
|
||||||
'OPTIONS' { http.Method.options }
|
|
||||||
else { http.Method.get }
|
|
||||||
}
|
|
||||||
url: path
|
url: path
|
||||||
data: body
|
data: body
|
||||||
}
|
}
|
||||||
@@ -216,14 +295,49 @@ fn create_usockets_context(method string, path string, params map[string]string,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取路径对应的所有中间件
|
// 快速 HTTP 方法解析(基于首字符和长度)
|
||||||
fn get_middlewares_for_path_usockets(app &Hono, path string) []ContextMiddleware {
|
@[inline]
|
||||||
|
fn parse_http_method_usockets(method string) http.Method {
|
||||||
|
len := method.len
|
||||||
|
if len == 0 {
|
||||||
|
return http.Method.get
|
||||||
|
}
|
||||||
|
|
||||||
|
// 基于首字符快速分支
|
||||||
|
match method[0] {
|
||||||
|
`G` {
|
||||||
|
if len == 3 { return http.Method.get }
|
||||||
|
}
|
||||||
|
`P` {
|
||||||
|
if len == 4 && method[1] == `O` { return http.Method.post }
|
||||||
|
if len == 3 && method[1] == `U` { return http.Method.put }
|
||||||
|
if len == 5 { return http.Method.patch }
|
||||||
|
}
|
||||||
|
`D` {
|
||||||
|
if len == 6 { return http.Method.delete }
|
||||||
|
}
|
||||||
|
`H` {
|
||||||
|
if len == 4 { return http.Method.head }
|
||||||
|
}
|
||||||
|
`O` {
|
||||||
|
if len == 7 { return http.Method.options }
|
||||||
|
}
|
||||||
|
else {}
|
||||||
|
}
|
||||||
|
return http.Method.get
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取路径对应的所有中间件(优化版:使用预排序的前缀列表)
|
||||||
|
fn get_middlewares_for_path_usockets_optimized(app &Hono, path string) []ContextMiddleware {
|
||||||
|
// 优化2:只有全局中间件时,直接返回引用(避免克隆)
|
||||||
|
if app.route_middlewares.len == 0 {
|
||||||
|
return app.context_middlewares
|
||||||
|
}
|
||||||
|
|
||||||
mut middlewares := app.context_middlewares.clone()
|
mut middlewares := app.context_middlewares.clone()
|
||||||
|
|
||||||
mut prefixes := app.route_middlewares.keys()
|
// 优化3:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
|
||||||
prefixes.sort(a.len < b.len)
|
for prefix in app.sorted_middleware_prefixes {
|
||||||
|
|
||||||
for prefix in prefixes {
|
|
||||||
if path.starts_with(prefix) || prefix == '/' {
|
if path.starts_with(prefix) || prefix == '/' {
|
||||||
if mws := app.route_middlewares[prefix] {
|
if mws := app.route_middlewares[prefix] {
|
||||||
middlewares << mws
|
middlewares << mws
|
||||||
@@ -234,6 +348,11 @@ fn get_middlewares_for_path_usockets(app &Hono, path string) []ContextMiddleware
|
|||||||
return middlewares
|
return middlewares
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 获取路径对应的所有中间件(保留旧版本兼容)
|
||||||
|
fn get_middlewares_for_path_usockets(app &Hono, path string) []ContextMiddleware {
|
||||||
|
return get_middlewares_for_path_usockets_optimized(app, path)
|
||||||
|
}
|
||||||
|
|
||||||
// 执行中间件链
|
// 执行中间件链
|
||||||
fn exec_middlewares_usockets(idx int, middlewares []ContextMiddleware, mut ctx Context, handler IHandler) http.Response {
|
fn exec_middlewares_usockets(idx int, middlewares []ContextMiddleware, mut ctx Context, handler IHandler) http.Response {
|
||||||
if idx < middlewares.len {
|
if idx < middlewares.len {
|
||||||
@@ -245,7 +364,7 @@ fn exec_middlewares_usockets(idx int, middlewares []ContextMiddleware, mut ctx C
|
|||||||
return handler.handle(mut ctx)
|
return handler.handle(mut ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送 uSockets 响应
|
// 发送 uSockets 响应 - 优化版
|
||||||
fn send_usockets_response(s usockets.Socket, ctx Context, response http.Response) {
|
fn send_usockets_response(s usockets.Socket, ctx Context, response http.Response) {
|
||||||
status_code := if ctx.status_code != 0 { ctx.status_code } else { response.status_code }
|
status_code := if ctx.status_code != 0 { ctx.status_code } else { response.status_code }
|
||||||
|
|
||||||
@@ -261,20 +380,22 @@ fn send_usockets_response(s usockets.Socket, ctx Context, response http.Response
|
|||||||
// 头部
|
// 头部
|
||||||
mut has_content_type := false
|
mut has_content_type := false
|
||||||
for key, value in ctx.headers {
|
for key, value in ctx.headers {
|
||||||
if key.to_lower() == 'content-length' {
|
// 使用快速大小写不敏感比较
|
||||||
|
key_len := key.len
|
||||||
|
if key_len == 14 && eq_ignore_case_usockets(key, 'content-length') {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
resp.write_string(key)
|
resp.write_string(key)
|
||||||
resp.write_string(': ')
|
resp.write_string(': ')
|
||||||
resp.write_string(value)
|
resp.write_string(value)
|
||||||
resp.write_string('\r\n')
|
resp.write_string('\r\n')
|
||||||
if key.to_lower() == 'content-type' {
|
if key_len == 12 && eq_ignore_case_usockets(key, 'content-type') {
|
||||||
has_content_type = true
|
has_content_type = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if content_type := response.header.get(.content_type) {
|
|
||||||
if !has_content_type {
|
if !has_content_type {
|
||||||
|
if content_type := response.header.get(.content_type) {
|
||||||
resp.write_string('Content-Type: ')
|
resp.write_string('Content-Type: ')
|
||||||
resp.write_string(content_type)
|
resp.write_string(content_type)
|
||||||
resp.write_string('\r\n')
|
resp.write_string('\r\n')
|
||||||
@@ -301,6 +422,25 @@ fn send_usockets_response(s usockets.Socket, ctx Context, response http.Response
|
|||||||
s.write_bytes(resp.str())
|
s.write_bytes(resp.str())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 大小写不敏感字符串比较(避免分配)
|
||||||
|
@[inline]
|
||||||
|
fn eq_ignore_case_usockets(a string, b string) bool {
|
||||||
|
if a.len != b.len {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i in 0 .. a.len {
|
||||||
|
ca := a[i]
|
||||||
|
cb := b[i]
|
||||||
|
// 转换为小写比较
|
||||||
|
la := if ca >= `A` && ca <= `Z` { ca + 32 } else { ca }
|
||||||
|
lb := if cb >= `A` && cb <= `Z` { cb + 32 } else { cb }
|
||||||
|
if la != lb {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// 获取状态码文本
|
// 获取状态码文本
|
||||||
fn get_status_text_usockets(code int) string {
|
fn get_status_text_usockets(code int) string {
|
||||||
return match code {
|
return match code {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
Module {
|
Module {
|
||||||
name: 'hono'
|
name: 'hono'
|
||||||
description: 'A high-performance V language web framework inspired by Hono.js, featuring hybrid routing, LRU cache, middleware support, and more.'
|
description: 'A high-performance V language web framework inspired by Hono.js, featuring hybrid routing, LRU cache, middleware support, and more.'
|
||||||
version: '0.3.6'
|
version: '0.3.8'
|
||||||
license: 'MIT'
|
license: 'MIT'
|
||||||
dependencies: []
|
dependencies: []
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user