Compare commits

...
23 Commits
Author SHA1 Message Date
meiseayoung 44ba82c194 chore: update v.mod version 2026-01-03 20:50:24 +08:00
meiseayoung 9eb360926b feat(usockets): optimize high concurrency support up to 10,000+ connections
- Increase uSockets listen() backlog from 512 to 16384 in bsd.c
- Add high concurrency test suite (5000-10000 concurrent connections)
- Add HIGH_CONCURRENCY.md documentation with optimization guide
- Add usockets/build.sh script for rebuilding uSockets library
- Update README with latest benchmark results

Performance (macOS M3 Max):
- 5,000 concurrent: 81,524 RPS, 100% success
- 10,000 concurrent: 24,198 RPS, 100% success

System requirements:
- kern.ipc.somaxconn >= 8192
- ulimit -n 65535
2026-01-03 20:45:30 +08:00
meiseayoung 3b8d21dd0d fix: update import path to VPM package name (meiseayoung.hono)
- Change all `import hono` to `import meiseayoung.hono` in code and docs
- Ensure compatibility with VPM installation via `v install meiseayoung.hono`
2026-01-02 22:05:12 +08:00
meiseayoung 43aae4f10d chore: update v.mod version 2026-01-02 21:51:01 +08:00
meiseayoung 05bb2d6c95 feat: cross-platform uSockets support and route cache optimization
1. Cross-platform uSockets configuration
   - Use @VMODROOT for portable library paths
   - Support macOS (arm64/x86_64), Windows, and Linux
   - Auto-detect Homebrew paths for libuv on macOS

2. Route cache optimization (3x performance boost)
   - Replace LRU cache with FastRouteCache for dynamic routes
   - Zero-overhead cache lookup (no TTL check, no LRU reordering)
   - Dynamic route performance: 30k -> 97k RPS

3. New test files
   - Go-based integration tests for picoev and uSockets
   - FastCache optimization validation tests
   - Benchmark comparison tools
2026-01-02 21:44:07 +08:00
meiseayoung 9aefe5714d chore: update v.mod version 2025-12-31 18:35:29 +08:00
meiseayoung 1fc22044c3 perf: optimize HTTP parsing with zero-allocation techniques
- Refactor parse_path_and_query() to use single-pass traversal instead of split()
- Add eq_ignore_case() and contains_ignore_case() to avoid to_lower() allocations
- Optimize HTTP method parsing with first-char branching (parse_http_method_fast)
- Optimize Keep-Alive header check to avoid string allocations
- Apply optimizations to all server backends: picoev, usockets, and app.v

Performance improvements:
- Query string parsing: 20-44% faster
- Keep-Alive check: 82-90% faster
- HTTP method parsing: eliminates string comparison overhead
- Response header processing: removes to_lower() allocations

All 20+ test suites pass with no regressions.
2025-12-31 18:34:46 +08:00
meiseayoung b478269d8e chore: update v.mod version 2025-12-31 17:38:29 +08:00
meiseayoung 69d1385ced perf: 0 middleware ignore copy 2025-12-31 17:37:51 +08:00
meiseayoung 1482b9c4d9 doc: add Framework Comparison 2025-12-31 16:04:44 +08:00
meiseayoung 0937dd268c chore: update v.mod version 2025-12-31 15:46:10 +08:00
meiseayoung 07382ab622 feat: integration usockets backend 2025-12-31 15:44:51 +08:00
meiseayoung 5375b7394f chore: update v.mod version 2025-12-30 21:40:39 +08:00
meiseayoung d0298ea577 fix: In high concurrency (200+), V-Hono experiences an error where the connection is reset problem 2025-12-30 19:23:09 +08:00
meiseayoung 8e1007a1b4 chore: update v.mod version 2025-12-30 18:42:02 +08:00
meiseayoung 6cdba50f36 fix: Remove duplicate response headers 2025-12-30 18:41:34 +08:00
meiseayoung 418ead392b chore: update v.mod version 2025-12-30 18:29:52 +08:00
meiseayoung e305abba2b fix: fix the issue of During ultra-high concurrency (5000 req, 200 concurrent) URL Params testing, stability issues were encountered (success rate only 0.24%). 2025-12-30 18:29:03 +08:00
meiseayoung e22f612f24 chore: update v.mod version 2025-12-30 17:32:05 +08:00
meiseayoung a38aeea614 perf: use picoev as default Server for improve response concurrency 2025-12-30 17:31:13 +08:00
meiseayoung ee2818782b chore: update v.mod version 2025-12-30 14:27:57 +08:00
meiseayoung 645d8c2dda feat: add redirect method 2025-12-30 14:25:35 +08:00
meiseayoung 6fe79d298d chore: use x.json2 module replace json_parser 2025-12-30 12:58:42 +08:00
116 changed files with 12582 additions and 315 deletions
+116 -5
View File
@@ -36,11 +36,114 @@ git clone https://github.com/meiseayoung/v-hono.git
cd v-hono
```
## Build & Run
### Standard Build (picoev backend)
```bash
v your_app.v -o app.exe
./app.exe
```
### High-Performance Build (uSockets backend)
For maximum performance with uSockets backend:
```bash
v -enable-globals -cc gcc -ldflags "-ldbghelp" your_app.v -o app.exe
./app.exe
```
**Note**: The `-enable-globals` flag is required for uSockets backend. The `-ldflags "-ldbghelp"` fixes Windows linking issues.
#### Windows Prerequisites
To use uSockets backend on Windows, you need:
1. **GCC (MinGW-w64)** - C compiler
```powershell
# Install via Scoop
scoop install mingw
# Or via Chocolatey
choco install mingw
# Or download from: https://www.mingw-w64.org/downloads/
```
2. **V Compiler** - Version 0.4.x or later
```powershell
# Install via Scoop
scoop install vlang
# Or download from: https://vlang.io/
```
3. **Verify Installation**
```powershell
gcc --version # Should show MinGW-w64 GCC
v version # Should show V 0.4.x
```
The uSockets library and libuv are pre-compiled and included in the `usockets/lib/` directory.
### Using uSockets Backend
```v
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello, World!')
})
// Use uSockets backend (high concurrency optimized)
app.listen_usockets(3000)
// Or use default picoev backend
// app.listen(':3000')
}
```
See [benchmark/README.md](benchmark/README.md) for performance benchmarks and [usockets/README.md](usockets/README.md) for uSockets integration details.
## High Concurrency Support
v-hono with uSockets backend supports **10,000+ concurrent connections** out of the box.
### Performance Results
| Concurrent | RPS | Avg Latency | P99 Latency | Success Rate |
|------------|-----|-------------|-------------|--------------|
| 5,000 | 81,524 | 60.77ms | 295.17ms | 100% |
| 6,000 | 56,290 | 98.46ms | 557.47ms | 100% |
| 7,000 | 42,895 | 130.04ms | 824.80ms | 100% |
| 8,000 | 30,537 | 165.27ms | 1058.05ms | 100% |
| 9,000 | 28,693 | 215.86ms | 1422.67ms | 100% |
| 10,000 | 24,198 | 240.90ms | 1602.10ms | 100% |
### System Configuration (macOS)
For optimal high-concurrency performance:
```bash
# Increase socket backlog limit
sudo sysctl -w kern.ipc.somaxconn=8192
# Increase file descriptor limit
ulimit -n 65535
```
See [docs/HIGH_CONCURRENCY.md](docs/HIGH_CONCURRENCY.md) for detailed optimization guide.
## Quick Start
```v
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -58,6 +161,11 @@ fn main() {
return c.json('{"user_id": "${user_id}"}')
})
// Redirect example
app.get('/old-page', fn (mut c hono.Context) http.Response {
return c.redirect('/new-page', 301)
})
app.listen(':3000')
}
```
@@ -67,7 +175,7 @@ fn main() {
```v
import net.http
import time
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -93,7 +201,7 @@ fn main() {
```v
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -121,7 +229,7 @@ fn main() {
```v
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -157,6 +265,7 @@ fn main() {
- `c.json(data)` - Return JSON response
- `c.html(data)` - Return HTML response
- `c.file(path)` - Return file response
- `c.redirect(url, status_code...)` - Redirect to URL (default status: 302)
- `c.status(code)` - Set response status code
- `c.params` - Route parameters
- `c.query` - Query parameters
@@ -179,7 +288,6 @@ v-hono/
├── config.v # Configuration management
├── logger.v # Logging system
├── multipart.v # Multipart form parsing
├── json_parser.v # JSON parsing utilities
├── upload.v # File upload handling
├── database.v # Database integration
├── auth.v # Authentication system
@@ -199,7 +307,10 @@ See the `examples/` directory for more examples:
- `examples/basic/` - Basic usage
- `examples/middleware/` - Middleware usage
- `examples/route_grouping/` - Route grouping
- `examples/redirect_demo.v` - Redirect functionality examples
## License
MIT License
+112 -15
View File
@@ -40,6 +40,10 @@ pub mut:
use_fast_router bool = true // 新增:是否使用快速路由器
context_middlewares []ContextMiddleware
route_middlewares map[string][]ContextMiddleware // 路由前缀对应的中间件
// 优化:预排序的中间件前缀列表(启动时计算一次)
sorted_middleware_prefixes []string
// 优化:标记是否有中间件(用于零中间件快速路径)
has_middlewares bool
}
// Context 中间件类型
@@ -185,6 +189,14 @@ pub fn (mut app Hono) all(path string, handler fn (mut Context) http.Response) {
// Context 中间件
pub fn (mut app Hono) use(mw ContextMiddleware) {
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 处理器
@@ -215,25 +227,31 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
}
}
// 解析 query
raw_query := url.query().to_map()
// 解析 query - 优化:直接使用 url.raw_query 避免额外解析
mut query_map := map[string]string{}
for key, values in raw_query {
if values.len > 0 {
query_map[key] = values[0]
}
if url.raw_query.len > 0 {
query_map = parse_query_string_app(url.raw_query)
}
// 缓存 method 字符串,避免多次调用 .str()
method_str := req.method.str()
// 尝试 Context 路由
// 优先使用快速路由器
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_map := route_match.params.clone()
// body
body := req.data
// 构造 Context
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)
// 洋葱模型递归执行中间件
@@ -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_map := route_match.params.clone()
// body
body := req.data
// 构造 Context
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)
// 洋葱模型递归执行中间件
@@ -258,13 +282,19 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
})
}
} 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_map := route_match.params.clone()
// body
body := req.data
// 构造 Context
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)
// 洋葱模型递归执行中间件
@@ -291,15 +321,17 @@ fn (mut s ServerHanler) handle(req http.Request) http.Response {
})
}
// 获取路径对应的所有中间件(全局 + 路由前缀匹配的)
// 获取路径对应的所有中间件(全局 + 路由前缀匹配的)- 优化版
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 prefixes := s.app.route_middlewares.keys()
prefixes.sort(a.len < b.len)
for prefix in prefixes {
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
for prefix in s.app.sorted_middleware_prefixes {
if path.starts_with(prefix) || prefix == '/' {
if mws := s.app.route_middlewares[prefix] {
middlewares << mws
@@ -335,6 +367,27 @@ fn (mut s ServerHanler) exec_context_middlewares(idx int, mut ctx Context, handl
}
pub fn (mut app Hono) listen(port string) {
// 解析端口号
port_num := port.trim(':').int()
if port_num <= 0 {
eprintln('[v-hono] Invalid port: ${port}')
return
}
// 优化:预计算中间件前缀排序
app.precompute_middleware_prefixes()
// 使用优化配置的 picoev 高性能服务器(支持高并发)
app.listen_picoev_with_config(PicoevConfig{
port: port_num
timeout_secs: 120 // 高并发场景需要更长超时
keepalive_timeout: 30 // Keep-Alive 超时 30 秒
max_keepalive_req: 10000 // 单连接最大请求数
})
}
// 使用传统 http.Server 启动(保留兼容性)
pub fn (mut app Hono) listen_http(port string) {
app.server.addr = port
app.server.handler = server_hanler_new(app)
// 增加超时配置以支持更好的 Keep-Alive
@@ -354,6 +407,7 @@ pub fn (mut app Hono) route(prefix string, mut subapp Hono) {
} else {
app.route_middlewares[prefix] = subapp.context_middlewares.clone()
}
app.has_middlewares = true
}
// 继承子应用的 notFound 和 onError 处理器(如果主应用没有设置)
@@ -490,5 +544,48 @@ pub fn Hono.new() Hono {
fast_router: FastRouter.new()
use_fast_router: true
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
}
+77
View File
@@ -0,0 +1,77 @@
# V-Hono Benchmark
Performance benchmarks for V-Hono web framework.
## Framework Comparison (500 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 |
### Performance Summary
- **v-hono (uSockets) vs veb**: **2.78x faster**, zero errors
- **v-hono (uSockets) vs picoev**: **25% faster**, better P99 latency
- **v-hono (picoev) vs veb**: **2.22x faster**, zero errors
## Running Benchmarks
### 1. Start Test Server
**uSockets backend:**
```bash
v -enable-globals -cc gcc -ldflags "-ldbghelp" benchmark/usockets_server.v -o server.exe
./server.exe
```
**Picoev backend:**
```bash
v -enable-globals examples/picoev_example.v -o server.exe
./server.exe
```
### 2. Run Integration Tests
```bash
go run benchmark/usockets_verify.go
```
### 3. Run Performance Tests
```bash
# 200 connections, 100K requests
go run tests/main.go -url "http://127.0.0.1:9998" -c 200 -n 100000
# 500 connections, 100K requests
go run tests/main.go -url "http://127.0.0.1:9998" -c 500 -n 100000
```
### 4. Quick Concurrent Test (PowerShell)
```powershell
powershell -File benchmark/quick_test.ps1
```
## Test Files
| File | Description |
|------|-------------|
| `usockets_server.v` | uSockets test server with full API |
| `usockets_verify.go` | Go integration test (17 test cases) |
| `quick_test.ps1` | PowerShell concurrent test script |
| `../tests/main.go` | Go performance benchmark tool |
## Test Coverage
The integration test (`usockets_verify.go`) covers:
- ✅ Basic GET routes (root, health, static)
- ✅ Dynamic routes (single/multi/nested params)
- ✅ Query parameters
- ✅ Response formats (JSON, HTML, custom status)
- ✅ HTTP methods (POST, PUT, DELETE)
- ✅ Error handling (404)
- ✅ Keep-Alive connections
- ✅ Throughput performance
+69
View File
@@ -0,0 +1,69 @@
# Quick concurrent test using runspaces
$url = "http://127.0.0.1:8888/"
$concurrency = 300
$requestsEach = 20
Write-Host "Testing $url with $concurrency concurrent workers, $requestsEach requests each"
Write-Host "Total: $($concurrency * $requestsEach) requests"
$runspacePool = [runspacefactory]::CreateRunspacePool(1, $concurrency)
$runspacePool.Open()
$scriptBlock = {
param($url, $count)
$s = 0; $f = 0
for ($i = 0; $i -lt $count; $i++) {
try {
$req = [System.Net.WebRequest]::Create($url)
$req.Timeout = 30000
$resp = $req.GetResponse()
if ($resp.StatusCode -eq "OK") { $s++ } else { $f++ }
$resp.Close()
} catch {
$f++
}
}
return @{Success=$s; Failed=$f}
}
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$runspaces = @()
for ($i = 0; $i -lt $concurrency; $i++) {
$ps = [powershell]::Create()
$ps.RunspacePool = $runspacePool
$ps.AddScript($scriptBlock).AddArgument($url).AddArgument($requestsEach) | Out-Null
$runspaces += @{PS=$ps; Handle=$ps.BeginInvoke()}
}
$totalSuccess = 0
$totalFailed = 0
foreach ($rs in $runspaces) {
$result = $rs.PS.EndInvoke($rs.Handle)
$totalSuccess += $result.Success
$totalFailed += $result.Failed
$rs.PS.Dispose()
}
$sw.Stop()
$runspacePool.Close()
$total = $totalSuccess + $totalFailed
$rps = [math]::Round($total * 1000 / $sw.ElapsedMilliseconds, 2)
$rate = [math]::Round($totalSuccess * 100 / $total, 2)
Write-Host ""
Write-Host "Results:"
Write-Host " Total: $total"
Write-Host " Success: $totalSuccess"
Write-Host " Failed: $totalFailed"
Write-Host " Duration: $($sw.ElapsedMilliseconds) ms"
Write-Host " RPS: $rps"
Write-Host " Success Rate: $rate%"
if ($totalFailed -eq 0) {
Write-Host "PASSED - No connection errors!" -ForegroundColor Green
} else {
Write-Host "FAILED - $totalFailed errors occurred" -ForegroundColor Red
}
+121
View File
@@ -0,0 +1,121 @@
// uSockets 测试服务器
// 用于集成测试验证 uSockets 后端功能
//
// 编译运行:
// v -enable-globals -cc gcc -ldflags "-ldbghelp" benchmark/usockets_test_server.v -o usockets_test.exe
// .\usockets_test.exe
module main
import meiseayoung.hono
import net.http
fn main() {
mut app := hono.Hono.new()
// 全局中间件 - 添加自定义响应头
app.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
mut resp := next(mut c)
c.headers['X-Middleware'] = 'applied'
return resp
})
// ==================== 基本路由 ====================
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello World')
})
app.get('/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
app.get('/api/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
// ==================== CRUD 路由 ====================
app.get('/api/users', fn (mut c hono.Context) http.Response {
return c.json('{"users": []}')
})
app.post('/api/users', fn (mut c hono.Context) http.Response {
c.status(201)
return c.json('{"created": true}')
})
app.get('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}"}')
})
app.put('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}", "updated": true}')
})
app.delete('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}", "deleted": true}')
})
app.patch('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}", "patched": true}')
})
// ==================== 多参数路由 ====================
app.get('/api/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
user_id := c.params['user_id'] or { '' }
post_id := c.params['post_id'] or { '' }
return c.json('{"user_id": "${user_id}", "post_id": "${post_id}"}')
})
app.get('/api/categories/:category/items/:item', fn (mut c hono.Context) http.Response {
category := c.params['category'] or { '' }
item := c.params['item'] or { '' }
return c.json('{"category": "${category}", "item": "${item}"}')
})
// ==================== 查询参数路由 ====================
app.get('/api/search', fn (mut c hono.Context) http.Response {
q := c.query['q'] or { '' }
limit := c.query['limit'] or { '10' }
page := c.query['page'] or { '1' }
return c.json('{"query": "${q}", "limit": ${limit}, "page": ${page}}')
})
// ==================== 响应格式路由 ====================
app.get('/api/json', fn (mut c hono.Context) http.Response {
return c.json('{"message": "JSON response"}')
})
app.get('/api/html', fn (mut c hono.Context) http.Response {
return c.html('<html><body><h1>HTML Response</h1></body></html>')
})
app.get('/api/created', fn (mut c hono.Context) http.Response {
c.status(201)
return c.json('{"created": true}')
})
app.get('/api/custom-header', fn (mut c hono.Context) http.Response {
c.headers['X-Custom-Header'] = 'custom-value'
return c.text('OK')
})
// ==================== 自定义 404 ====================
app.not_found(fn (mut c hono.Context) http.Response {
c.status(404)
return c.json('{"error": "Not Found", "path": "${c.path}"}')
})
// 启动 uSockets 服务器
println('[usockets-test-server] Starting on port 9998...')
app.listen_usockets(9998)
}
+468
View File
@@ -0,0 +1,468 @@
// uSockets 功能验证测试
// go run benchmark/usockets_verify.go
package main
import (
"fmt"
"io"
"net/http"
"strings"
"time"
)
const baseURL = "http://127.0.0.1:9998"
func main() {
fmt.Println("╔═══════════════════════════════════════════════════════════════╗")
fmt.Println("║ uSockets 集成测试 ║")
fmt.Println("╚═══════════════════════════════════════════════════════════════╝")
fmt.Println()
client := &http.Client{Timeout: 5 * time.Second}
// 检查服务器
fmt.Print("🔍 检查测试服务器... ")
if !checkServer(client) {
fmt.Println("❌ 服务器未运行")
return
}
fmt.Println("✅")
fmt.Println()
total, passed, failed := 0, 0, 0
var errors []string
// 1. 基本 GET 路由测试
fmt.Println("📦 1. 基本 GET 路由测试")
total++
fmt.Print(" 🧪 GET 根路径... ")
if checkGetRoot(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "GET 根路径")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 GET 健康检查... ")
if checkGetHealth(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "GET 健康检查")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 GET 静态路由... ")
if checkGetStatic(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "GET 静态路由")
fmt.Println("❌")
}
fmt.Println()
// 2. 动态路由测试
fmt.Println("📦 2. 动态路由测试")
total++
fmt.Print(" 🧪 单参数路由... ")
if checkSingleParam(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "单参数路由")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 多参数路由... ")
if checkMultiParams(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "多参数路由")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 嵌套参数路由... ")
if checkNestedParams(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "嵌套参数路由")
fmt.Println("❌")
}
fmt.Println()
// 3. 查询参数测试
fmt.Println("📦 3. 查询参数测试")
total++
fmt.Print(" 🧪 单个查询参数... ")
if checkSingleQuery(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "单个查询参数")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 多个查询参数... ")
if checkMultiQuery(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "多个查询参数")
fmt.Println("❌")
}
fmt.Println()
// 4. 响应格式测试
fmt.Println("📦 4. 响应格式测试")
total++
fmt.Print(" 🧪 JSON 响应... ")
if checkJSONResponse(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "JSON 响应")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 HTML 响应... ")
if checkHTMLResponse(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "HTML 响应")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 自定义状态码 201... ")
if checkCustomStatus(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "自定义状态码 201")
fmt.Println("❌")
}
fmt.Println()
// 5. HTTP 方法测试
fmt.Println("📦 5. HTTP 方法测试")
total++
fmt.Print(" 🧪 POST 请求... ")
if checkPOST(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "POST 请求")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 PUT 请求... ")
if checkPUT(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "PUT 请求")
fmt.Println("❌")
}
total++
fmt.Print(" 🧪 DELETE 请求... ")
if checkDELETE(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "DELETE 请求")
fmt.Println("❌")
}
fmt.Println()
// 6. 错误处理测试
fmt.Println("📦 6. 错误处理测试")
total++
fmt.Print(" 🧪 404 未找到... ")
if checkNotFound(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "404 未找到")
fmt.Println("❌")
}
fmt.Println()
// 7. Keep-Alive 测试
fmt.Println("📦 7. Keep-Alive 连接测试")
total++
fmt.Print(" 🧪 连接复用... ")
if checkKeepAlive(client) {
passed++
fmt.Println("✅")
} else {
failed++
errors = append(errors, "连接复用")
fmt.Println("❌")
}
fmt.Println()
// 8. 性能测试
fmt.Println("📦 8. 性能测试")
total++
fmt.Print(" 🧪 吞吐量测试... ")
rps := checkThroughput(client)
if rps > 100 {
passed++
fmt.Printf("✅ (%.0f req/s)\n", rps)
} else {
failed++
errors = append(errors, "吞吐量")
fmt.Printf("❌ (%.0f req/s)\n", rps)
}
fmt.Println()
// 输出总结
fmt.Println("═══════════════════════════════════════════════════════════════")
fmt.Printf("📊 测试结果: %d/%d 通过\n", passed, total)
if failed > 0 {
fmt.Println("❌ 失败的测试:")
for _, err := range errors {
fmt.Printf(" - %s\n", err)
}
} else {
fmt.Println("🎉 所有测试通过!uSockets 后端验证成功!")
}
fmt.Println("═══════════════════════════════════════════════════════════════")
}
func checkServer(client *http.Client) bool {
resp, err := client.Get(baseURL + "/health")
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == 200
}
func getBody(resp *http.Response) string {
body, _ := io.ReadAll(resp.Body)
return string(body)
}
func checkGetRoot(client *http.Client) bool {
resp, err := client.Get(baseURL + "/")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "Hello")
}
func checkGetHealth(client *http.Client) bool {
resp, err := client.Get(baseURL + "/health")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && body == "OK"
}
func checkGetStatic(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/health")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && body == "OK"
}
func checkSingleParam(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/users/456")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "456")
}
func checkMultiParams(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/users/123/posts/789")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "123") && strings.Contains(body, "789")
}
func checkNestedParams(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/categories/tech/items/laptop")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "tech") && strings.Contains(body, "laptop")
}
func checkSingleQuery(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/search?q=test")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "test")
}
func checkMultiQuery(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/search?q=hello&limit=10&page=1")
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "hello")
}
func checkJSONResponse(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/json")
if err != nil {
return false
}
defer resp.Body.Close()
ct := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(ct, "application/json")
}
func checkHTMLResponse(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/html")
if err != nil {
return false
}
defer resp.Body.Close()
ct := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(ct, "text/html")
}
func checkCustomStatus(client *http.Client) bool {
resp, err := client.Get(baseURL + "/api/created")
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == 201
}
func checkPOST(client *http.Client) bool {
resp, err := client.Post(baseURL+"/api/users", "application/json", nil)
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 201 && strings.Contains(body, "created")
}
func checkPUT(client *http.Client) bool {
req, _ := http.NewRequest("PUT", baseURL+"/api/users/123", nil)
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "updated")
}
func checkDELETE(client *http.Client) bool {
req, _ := http.NewRequest("DELETE", baseURL+"/api/users/123", nil)
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
body := getBody(resp)
return resp.StatusCode == 200 && strings.Contains(body, "deleted")
}
func checkNotFound(client *http.Client) bool {
resp, err := client.Get(baseURL + "/nonexistent/path")
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == 404
}
func checkKeepAlive(client *http.Client) bool {
for i := 0; i < 10; i++ {
resp, err := client.Get(baseURL + "/health")
if err != nil {
return false
}
resp.Body.Close()
if resp.StatusCode != 200 {
return false
}
}
return true
}
func checkThroughput(client *http.Client) float64 {
start := time.Now()
success := 0
requests := 200
for i := 0; i < requests; i++ {
resp, err := client.Get(baseURL + "/health")
if err != nil {
continue
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
if resp.StatusCode == 200 {
success++
}
}
elapsed := time.Since(start).Seconds()
return float64(success) / elapsed
}
+68
View File
@@ -336,3 +336,71 @@ pub fn (mut cache ContextLRUCache) clear() {
cache.size = 0
cache.last_cleanup = time.now().unix()
}
// ============================================================================
// 高性能路由缓存 - 专为路由匹配优化
// ============================================================================
// 特点:
// 1. 无 TTL 检查(路由不会过期)
// 2. 无 LRU 移动(简单 map 查找)
// 3. 固定大小,满了就清空重建
// 4. 零开销的 get 操作
pub struct FastRouteCache {
mut:
cache map[string]ContextRouteMatch
capacity int
enabled bool = true
}
pub fn FastRouteCache.new(capacity int) FastRouteCache {
return FastRouteCache{
cache: map[string]ContextRouteMatch{}
capacity: capacity
enabled: true
}
}
// 快速获取 - 零开销
@[inline]
pub fn (cache &FastRouteCache) get(key string) ?ContextRouteMatch {
if !cache.enabled {
return none
}
if result := cache.cache[key] {
return result
}
return none
}
// 快速设置
@[inline]
pub fn (mut cache FastRouteCache) put(key string, value ContextRouteMatch) {
if !cache.enabled {
return
}
// 如果满了,清空重建(比 LRU 淘汰更快)
if cache.cache.len >= cache.capacity {
cache.cache.clear()
}
cache.cache[key] = value
}
// 获取统计
pub fn (cache &FastRouteCache) get_stats() (int, int) {
return cache.cache.len, cache.capacity
}
// 清空缓存
pub fn (mut cache FastRouteCache) clear() {
cache.cache.clear()
}
// 启用/禁用
pub fn (mut cache FastRouteCache) set_enabled(enabled bool) {
cache.enabled = enabled
if !enabled {
cache.clear()
}
}
+115
View File
@@ -0,0 +1,115 @@
# v-hono 高并发优化指南
## 概述
v-hono 使用 uSockets 作为高性能网络后端,经过优化后可以稳定支持 **10,000+ 并发连接**。
## 性能测试结果
| 并发数 | RPS | 平均延迟 | P99延迟 | 成功率 |
|--------|-----|----------|---------|--------|
| 5,000 | 81,524 | 60.77ms | 295.17ms | 100% |
| 6,000 | 56,290 | 98.46ms | 557.47ms | 100% |
| 7,000 | 42,895 | 130.04ms | 824.80ms | 100% |
| 8,000 | 30,537 | 165.27ms | 1058.05ms | 100% |
| 9,000 | 28,693 | 215.86ms | 1422.67ms | 100% |
| 10,000 | 24,198 | 240.90ms | 1602.10ms | 100% |
测试环境:macOS (Apple Silicon M3 Max)
**重要提示**:每次测试后需等待 60 秒让 TIME_WAIT 连接释放,否则会影响下一次测试结果。
## 关键优化
### 1. uSockets backlog 参数
原始 uSockets 库的 `listen()` backlog 参数硬编码为 512,限制了高并发能力。
**修复位置**:`v-hono/usockets/src/bsd.c` (第 532 行和第 578 行)
```c
// 修改前
listen(listenFd, 512)
// 修改后
listen(listenFd, 16384)
```
修改后的源码保存在 `v-hono/usockets/src/bsd.c`,编译后的库文件在 `v-hono/lib/libusockets_full.a`。
**重新编译**:运行 `v-hono/usockets/build.sh` 脚本。
### 2. 系统参数配置
macOS 需要调整以下系统参数:
```bash
# 查看当前值
sysctl kern.ipc.somaxconn
# 临时修改(重启后失效)
sudo sysctl -w kern.ipc.somaxconn=8192
# 永久修改(添加到 /etc/sysctl.conf)
kern.ipc.somaxconn=8192
```
**注意**:实际 backlog 值会被 `kern.ipc.somaxconn` 截断,所以系统参数也需要相应调整。
## 重新编译 uSockets(可选)
如果需要自定义 backlog 值,可以重新编译 uSockets:
```bash
# 1. 克隆 uSockets
git clone https://github.com/uNetworking/uSockets.git
# 2. 修改 src/bsd.c 中的 listen 调用
# 将 listen(listenFd, 512) 改为 listen(listenFd, 16384)
# 3. 编译(macOS with libuv)
WITH_LIBUV=1 CFLAGS="-I/opt/homebrew/include" make
# 4. 复制到 v-hono
cp uSockets.a /path/to/v-hono/lib/libusockets_full.a
# 5. 重新编译 v-hono 应用
v -enable-globals -prod -o your_app your_app.v
```
## 使用建议
1. **生产环境**:建议使用 uSockets 后端(`app.listen_usockets(port)`)
2. **系统调优**:确保 `kern.ipc.somaxconn` >= 8192
3. **文件描述符**:服务器和客户端都需要设置 `ulimit -n 65535`
4. **启动命令**:`ulimit -n 65535 && ./your_server`
## 高并发测试
运行高并发测试:
```bash
# 启动服务器
ulimit -n 65535 && ./bench_server_usockets
# 运行测试 (5000-10000 并发)
ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go
# 单独测试某个级别
ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go 8000
```
## 问题排查
如果高并发测试失败,检查:
1. 服务器是否正常响应:`curl http://localhost:8080/health`
2. 系统参数:`sysctl kern.ipc.somaxconn`
3. 文件描述符限制:`ulimit -n`
4. 测试客户端是否有端口耗尽问题
## 版本信息
- uSockets backlog: 16384
- 测试日期: 2026-01-03
- 测试通过最大并发: 10,000(不使用渐进式启动)
+45 -23
View File
@@ -1,40 +1,62 @@
# 已知问题
## 1. HTTP Keep-Alive 连接复用不支持
## 1. HTTP Keep-Alive 连接复用优化
**状态**: 等待 V 语言官方修复
**状态**: 已优化 (2025-12-30)
**问题描述**:
每次 HTTP 请求响应时间约 300ms,其中大部分时间消耗在 TCP 连接建立上。即使响应头中包含 `Connection: keep-alive`,连接也无法复用。
**现象**:
- 快速连续发送请求:每次都慢(~300ms)
- 慢速发送请求:快慢交替(复用时快,超时后重建连接时慢)
在超高并发(5000 req, 200 concurrent)的 URL Params 测试中出现稳定性问题(成功率仅 0.24%)。
**根本原因**:
V 语言标准库 `net.http.Server` 的 `handle_conn` 函数在每次请求处理完成后都会立即关闭连接:
1. picoev 的 `max_fds = 1024` 限制了并发连接数
2. 虽然设置了 `Connection: keep-alive` 头,但连接管理不够优化
3. 高并发下客户端端口耗尽(TCP TIME_WAIT 状态累积)
4. 缺少 `Content-Length` 头导致客户端无法正确解析响应边界
**已实施的优化**:
### 1. 增强 Keep-Alive 支持
- 添加 `Keep-Alive` 响应头,包含 `timeout` 和 `max` 参数
- 检测客户端 Keep-Alive 请求头
- 根据客户端请求决定是否保持连接
### 2. 响应头优化
- 始终设置 `Content-Length` 头,帮助客户端正确解析响应边界
- 优化 `Content-Type` 默认值
### 3. 高并发配置
新增 `HighConcurrencyConfig` 和 `listen_high_concurrency()` 方法:
```v
// F:\v\vlib\net\http\server.v
fn (mut w HandlerWorker) handle_conn(mut conn net.TcpConn) {
defer {
conn.close() or { eprintln('close() failed: ${err}') } // 每次请求后关闭连接
}
// ... 处理单个请求 ...
// 使用高并发优化配置启动
app.listen_high_concurrency(8081)
// 或使用自定义配置
config := hono.HighConcurrencyConfig{
port: 8081
timeout_secs: 5 // 较短超时
keepalive_timeout: 3 // Keep-Alive 超时
max_keepalive_req: 500 // 单连接最大请求数
}
app.listen_high_concurrency_with_config(config)
```
**影响**:
- 无法实现 HTTP/1.1 Keep-Alive 连接复用
- 每次请求都需要重新建立 TCP 连接(三次握手)
- 高并发场景下性能受限
### 4. 服务器配置优化
- 降低默认超时时间(8秒 -> 5秒)以更快释放连接
- 增大写缓冲区(8KB -> 64KB)
- 添加 TCP_NODELAY 配置选项
**临时解决方案**:
- 在服务器前部署支持 Keep-Alive 的反向代理(如 nginx)
- 或等待 V 语言官方修复此问题
**使用建议**:
1. 高并发场景使用 `--high-concurrency` 或 `-hc` 参数启动服务器
2. 在服务器前部署支持 Keep-Alive 的反向代理(如 nginx)
3. 使用压力测试工具验证: `v run examples/stress_test.v`
**picoev 底层限制**:
- `max_fds = 1024` 是 picoev 的硬编码限制
- 真正的连接复用需要 picoev 底层支持
- 建议关注 V 语言官方对 picoev 的更新
**跟踪**:
- V 语言 GitHub: https://github.com/vlang/v
- 相关文件: `vlib/net/http/server.v`
- 相关文件: `vlib/picoev/picoev.v`
**发现日期**: 2025-12-26
**更新日期**: 2025-12-30
+83 -9
View File
@@ -1,36 +1,55 @@
# vweb vs v-hono 性能对比测试
# veb vs v-hono 性能对比测试
## 测试文件说明
| 文件 | 说明 |
|------|------|
| `benchmark_vweb_vs_hono.v` | 路由匹配性能测试(纯路由,不启动服务器) |
| `server_vweb.v` | vweb HTTP 服务器示例(端口 8080) |
| `benchmark_veb_vs_hono.v` | 路由匹配性能测试(纯路由,不启动服务器) |
| `server_veb.v` | veb HTTP 服务器示例(端口 8080)- V 语言官方新版 web 框架 |
| `server_vweb.v` | vweb HTTP 服务器示例(端口 8080)- 旧版兼容 |
| `server_hono.v` | v-hono HTTP 服务器示例(端口 8081) |
| `http_benchmark.v` | HTTP 压测工具(自动对比两个服务器) |
| `run_benchmark.ps1` | Windows PowerShell 一键测试脚本 |
## 快速开始
### Windows 用户(推荐)
```powershell
cd examples
.\run_benchmark.ps1
```
### 1. 路由匹配性能测试
```bash
v run benchmark_vweb_vs_hono.v
cd examples
v run benchmark_veb_vs_hono.v
```
### 2. HTTP 服务器压测
启动 vweb 服务器:
#### 方式一:使用内置压测工具
终端 1 - 启动 veb 服务器:
```bash
v run server_vweb.v
v run server_veb.v
```
启动 v-hono 服务器(另一个终端):
终端 2 - 启动 v-hono 服务器:
```bash
v run server_hono.v
```
使用 wrk 或 ab 进行压测:
终端 3 - 运行压测:
```bash
# 测试 vweb
v run http_benchmark.v
```
#### 方式二:使用 wrk 或 ab
```bash
# 测试 veb
wrk -t4 -c100 -d10s http://localhost:8080/
wrk -t4 -c100 -d10s http://localhost:8080/api/users/123
@@ -45,6 +64,15 @@ ab -n 10000 -c 100 http://localhost:8080/
ab -n 10000 -c 100 http://localhost:8081/
```
### 3. 编译优化版本(推荐用于正式压测)
```bash
cd examples
v -prod server_veb.v -o server_veb.exe
v -prod server_hono.v -o server_hono.exe
v -prod http_benchmark.v -o http_benchmark.exe
```
## 测试结果分析
### 路由匹配性能
@@ -71,3 +99,49 @@ ab -n 10000 -c 100 http://localhost:8081/
| `GET /api/users/:id/posts` | 动态 | 获取用户的帖子 |
| `GET /api/users/:user_id/posts/:post_id` | 动态 | 获取特定帖子 |
| `GET /api/categories/:cat/items/:item` | 动态 | 获取分类商品 |
## 测试结果分析
### 路由匹配性能
| 路由类型 | SimpleRouter (模拟 veb) | v-hono FastRouter |
|----------|-------------------------|-------------------|
| 静态路由 | ~1000 ns/op | ~9500 ns/op |
| 动态路由 | ~15000-25000 ns/op | ~9500 ns/op |
### HTTP 吞吐量(参考值)
| 端点类型 | veb | v-hono | 说明 |
|----------|-----|--------|------|
| 静态路由 | ~15000 req/s | ~12000 req/s | veb 略快 |
| 动态路由 | ~8000 req/s | ~10000 req/s | v-hono 更稳定 |
> 注:实际性能取决于硬件配置和系统负载
## 结论
- **静态路由**:veb/SimpleRouter 使用 map 直接查找,通常更快
- **动态路由**:v-hono 使用 Trie + 缓存,性能更稳定
- **v-hono 优势**:动态路由性能一致,不随路由复杂度增加而显著下降
- **veb 优势**:官方支持,与 V 语言生态集成更好
## 测试端点
| 端点 | 类型 | 说明 |
|------|------|------|
| `GET /` | 静态 | Hello World |
| `GET /api/health` | 静态 | 健康检查 |
| `GET /api/users` | 静态 | 获取用户列表 |
| `POST /api/users` | 静态 | 创建用户 |
| `GET /api/users/:id` | 动态 | 获取单个用户 |
| `GET /api/users/:id/posts` | 动态 | 获取用户的帖子 |
| `GET /api/users/:user_id/posts/:post_id` | 动态 | 获取特定帖子 |
| `GET /api/categories/:cat/items/:item` | 动态 | 获取分类商品 |
## 注意事项
1. **veb vs vweb**:veb 是 V 语言官方的新版 web 框架,替代了旧的 vweb
2. **编译优化**:正式压测时请使用 `-prod` 编译优化版本
3. **预热**:测试前建议先发送一些请求预热服务器
4. **环境隔离**:压测时关闭其他占用 CPU 的程序
+151
View File
@@ -0,0 +1,151 @@
# Redirect 功能文档
v-hono 现在支持 HTTP 重定向功能,与 Hono.js 的 `c.redirect()` API 兼容。
## 基本用法
### 基本重定向 (302 Found)
```v
app.get('/old-page', fn (mut c hono.Context) hono.Response {
return c.redirect('https://example.com/new-page')
})
```
### 带状态码的重定向
```v
// 301 Moved Permanently - 永久重定向
app.get('/old-url', fn (mut c hono.Context) hono.Response {
return c.redirect('https://example.com/new-url', 301)
})
// 303 See Other - 通常用于 POST 后重定向
app.post('/form-submit', fn (mut c hono.Context) hono.Response {
// 处理表单数据...
return c.redirect('/success', 303)
})
// 307 Temporary Redirect - 临时重定向,保持请求方法
app.get('/temp-redirect', fn (mut c hono.Context) hono.Response {
return c.redirect('/new-location', 307)
})
// 308 Permanent Redirect - 永久重定向,保持请求方法
app.get('/perm-redirect', fn (mut c hono.Context) hono.Response {
return c.redirect('/new-location', 308)
})
```
## API 参考
### `c.redirect(url, status_code...)`
**参数:**
- `url` (string): 重定向的目标 URL,可以是绝对 URL 或相对路径
- `status_code` (int, 可选): HTTP 状态码,默认为 302
**返回值:**
- `http.Response`: 包含适当状态码和 Location 头的 HTTP 响应
**支持的状态码:**
- `301` - Moved Permanently (永久重定向)
- `302` - Found (临时重定向,默认)
- `303` - See Other (查看其他位置)
- `307` - Temporary Redirect (临时重定向,保持方法)
- `308` - Permanent Redirect (永久重定向,保持方法)
## 使用场景
### 1. 基本页面重定向
```v
app.get('/home', fn (mut c hono.Context) hono.Response {
return c.redirect('/')
})
```
### 2. 条件重定向
```v
app.get('/mobile-check', fn (mut c hono.Context) hono.Response {
user_agent := c.req.header.get_custom('User-Agent') or { '' }
if user_agent.contains('Mobile') {
return c.redirect('/mobile')
} else {
return c.redirect('/desktop')
}
})
```
### 3. 表单提交后重定向 (PRG 模式)
```v
app.post('/login', fn (mut c hono.Context) hono.Response {
// 验证用户凭据...
if login_successful {
return c.redirect('/dashboard', 303)
} else {
return c.redirect('/login?error=1', 303)
}
})
```
### 4. URL 规范化
```v
app.get('/UPPERCASE', fn (mut c hono.Context) hono.Response {
return c.redirect('/lowercase', 301)
})
app.get('/trailing-slash/', fn (mut c hono.Context) hono.Response {
return c.redirect('/trailing-slash', 301)
})
```
### 5. 外部重定向
```v
app.get('/external', fn (mut c hono.Context) hono.Response {
return c.redirect('https://external-site.com')
})
```
## 重定向状态码说明
| 状态码 | 名称 | 说明 | 浏览器行为 |
|--------|------|------|------------|
| 301 | Moved Permanently | 永久重定向,搜索引擎会更新索引 | 缓存重定向,保持原方法 |
| 302 | Found | 临时重定向,默认状态码 | 不缓存,可能改变方法为 GET |
| 303 | See Other | 查看其他位置,常用于 POST 后重定向 | 总是使用 GET 方法 |
| 307 | Temporary Redirect | 临时重定向,保持原请求方法 | 不缓存,保持原方法 |
| 308 | Permanent Redirect | 永久重定向,保持原请求方法 | 缓存重定向,保持原方法 |
## 最佳实践
1. **使用适当的状态码**: 根据重定向的性质选择正确的状态码
2. **避免重定向循环**: 确保重定向不会形成无限循环
3. **使用绝对 URL**: 对于外部重定向,使用完整的 URL
4. **SEO 考虑**: 对于永久性的 URL 变更使用 301 状态码
5. **POST 后重定向**: 使用 303 状态码避免重复提交
## 示例应用
查看 `examples/redirect_demo.v` 获取完整的使用示例。
## 与 Hono.js 的兼容性
v-hono 的 `c.redirect()` 方法与 Hono.js 的 API 完全兼容:
```javascript
// Hono.js
c.redirect('https://example.com')
c.redirect('https://example.com', 301)
```
```v
// v-hono
c.redirect('https://example.com')
c.redirect('https://example.com', 301)
```
+1 -1
View File
@@ -11,7 +11,7 @@
#### 使用方式
```v
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
+171
View File
@@ -0,0 +1,171 @@
# veb 优化分析 - v-hono 可借鉴的优化策略
## veb 核心优化策略
### 1. 使用 picoev 事件驱动模型
veb 使用 `picoev` 作为底层事件循环,这是一个高性能的事件驱动 I/O 库。
```v
// veb 使用 picoev 处理连接
mut pico := picoev.new(
port: params.port
raw_cb: ev_callback[A, X]
user_data: pico_context
timeout_secs: params.timeout_in_seconds
family: params.family
host: params.host
)!
pico.serve()
```
**v-hono 可借鉴:** 考虑使用 picoev 替代 `net.http.Server`,可以显著提升并发性能。
### 2. 预分配缓冲区
veb 预先分配了读写缓冲区,避免每次请求都分配内存:
```v
// 预分配缓冲区
pico_context.buf = unsafe { malloc_noscan(picoev.max_fds * max_read + 1) }
pico_context.incomplete_requests = []http.Request{len: picoev.max_fds}
pico_context.file_responses = []FileResponse{len: picoev.max_fds}
pico_context.string_responses = []StringResponse{len: picoev.max_fds}
```
**v-hono 可借鉴:** 使用对象池或预分配缓冲区减少 GC 压力。
### 3. 编译时路由生成
veb 使用 V 语言的编译时反射 `$for` 在编译时生成路由表:
```v
fn generate_routes[A, X](app &A) !map[string]Route {
mut routes := map[string]Route{}
$for method in A.methods {
$if method.return_type is Result {
http_methods, route_path, host := parse_attrs(method.name, method.attrs)
routes[method.name] = Route{
methods: http_methods
path: route_path
host: host
}
}
}
return routes
}
```
**v-hono 可借鉴:** 虽然 v-hono 使用运行时路由注册,但可以考虑在启动时预编译所有路由模式。
### 4. 快速响应发送
veb 使用 `strings.Builder` 构建响应,避免字符串拼接:
```v
fn fast_send_resp_header(mut conn net.TcpConn, resp http.Response) ! {
mut sb := strings.new_builder(resp.body.len + 200)
sb.write_string('HTTP/')
sb.write_string(resp.http_version)
sb.write_string(' ')
sb.write_decimal(resp.status_code)
// ...
send_string(mut conn, sb.str())!
}
```
**v-hono 可借鉴:** 使用 `strings.Builder` 替代字符串拼接构建 HTTP 响应。
### 5. 零拷贝文件传输 (sendfile)
veb 在 Linux/FreeBSD 上使用 `sendfile` 系统调用:
```v
$if linux || freebsd {
bytes_written := sendfile(fd, params.file_responses[fd].file.fd, bytes_to_write)
}
```
**v-hono 可借鉴:** 对于静态文件服务,使用 sendfile 可以避免用户态和内核态之间的数据拷贝。
### 6. 智能连接管理
veb 根据响应大小选择不同的发送策略:
```v
// 小响应直接发送
if completed_context.res.body.len < max_read {
fast_send_resp(mut conn, completed_context.res) or {}
} else {
// 大响应使用流式传输
params.string_responses[fd].open = true
params.string_responses[fd].str = completed_context.res.body
// 注册写事件
pv.add(fd, picoev.picoev_write, ...)
}
```
**v-hono 可借鉴:** 根据响应大小采用不同的发送策略。
### 7. 路由匹配优化
veb 的路由匹配策略:
1. 先匹配精确路由(不含参数)
2. 再匹配参数路由
3. 使用简单的字符串分割和比较
```v
// 精确匹配优先
if !route.path.contains('/:') && url_words == route_words {
// 直接调用处理器
app.$method(mut user_context)
return
}
// 参数路由匹配
if params := route_matches(url_words, route_words) {
app.$method(mut user_context, method_args)
return
}
```
**v-hono 可借鉴:** v-hono 已经实现了类似的静态/动态路由分离,但可以进一步优化参数提取。
### 8. 内存管理
veb 使用 `@[manualfree]` 和 `defer` 进行精细的内存管理:
```v
@[manualfree]
pub fn (mut sr StringResponse) done() {
sr.open = false
sr.pos = 0
sr.should_close_conn = false
unsafe { sr.str.free() }
}
```
**v-hono 可借鉴:** 对于频繁分配的对象,考虑手动内存管理。
## v-hono 优化建议
### 高优先级
1. **使用 picoev 替代 http.Server** - 这是最大的性能提升点
2. **预分配缓冲区** - 减少每次请求的内存分配
3. **使用 strings.Builder** - 优化响应构建
### 中优先级
4. **实现真正的 Keep-Alive** - 需要 picoev 支持
5. **优化 LRU 缓存** - 减少时间调用,使用更高效的数据结构
6. **路由预编译** - 启动时预编译所有正则表达式
### 低优先级
7. **sendfile 支持** - 静态文件零拷贝传输
8. **响应大小分级处理** - 小响应直接发送,大响应流式传输
9. **手动内存管理** - 对热点路径进行优化
## 性能对比总结
| 特性 | veb | v-hono | 差距原因 |
|------|-----|--------|----------|
| 事件模型 | picoev | http.Server | picoev 更高效 |
| Keep-Alive | ✅ 支持 | ❌ 不支持 | http.Server 限制 |
| 缓冲区 | 预分配 | 按需分配 | 内存分配开销 |
| 路由生成 | 编译时 | 运行时 | 启动时间 vs 运行时 |
| 文件传输 | sendfile | 读取+发送 | 零拷贝 vs 双拷贝 |
## 结论
v-hono 与 veb 的主要性能差距来自底层 HTTP 服务器实现。如果 v-hono 切换到 picoev,性能应该能接近甚至超过 veb。
+2 -2
View File
@@ -1,6 +1,6 @@
module main
import hono
import meiseayoung.hono
import net.http
import x.json2
@@ -100,7 +100,7 @@ fn main() {
})
println('🚀 用户角色菜单管理系统已启动')
println('📱 访问地址: http://localhost:3000')
println('📱 访问地址: http://127.0.0.1:3000')
println('')
println('📋 示例用户:')
println(' 用户名: admin, 密码: admin123, 角色: admin')
+2 -2
View File
@@ -4,7 +4,7 @@
module main
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -42,6 +42,6 @@ fn main() {
return c.json('{"received": "${body}"}')
})
println('Server starting on http://localhost:3000')
println('Server starting on http://127.0.0.1:3000')
app.listen(':3000')
}
+344
View File
@@ -0,0 +1,344 @@
// veb vs v-hono 性能对比测试
// 运行: v run benchmark_veb_vs_hono.v
//
// 测试内容:
// 1. 路由匹配性能(纯路由,不启动服务器)
// 2. 静态路由 vs 动态路由性能对比
// 3. 缓存命中率分析
module main
import time
import meiseayoung.hono
import net.http
// ============================================
// 测试配置
// ============================================
const iterations = 10000
const warmup_iterations = 1000
// 测试路径
const static_paths = [
'/',
'/api/health',
'/api/users',
]
const dynamic_paths = [
'/api/users/123',
'/api/users/456/posts',
'/api/users/789/posts/101',
'/api/categories/electronics/items/phone',
]
// ============================================
// 简单路由器(模拟 veb 的路由匹配方式)
// ============================================
struct SimpleRouter {
mut:
static_routes map[string]string
dynamic_routes []DynamicRoute
}
struct DynamicRoute {
pattern string
param_names []string
}
fn SimpleRouter.new() SimpleRouter {
return SimpleRouter{
static_routes: map[string]string{}
dynamic_routes: []DynamicRoute{}
}
}
fn (mut r SimpleRouter) add_static(path string) {
r.static_routes[path] = path
}
fn (mut r SimpleRouter) add_dynamic(pattern string, param_names []string) {
r.dynamic_routes << DynamicRoute{pattern, param_names}
}
// 简单的动态路由匹配(模拟 veb 的线性扫描方式)
fn (r SimpleRouter) match_route(path string) (bool, map[string]string) {
// 1. 先尝试静态匹配
if path in r.static_routes {
return true, map[string]string{}
}
// 2. 动态路由匹配(线性扫描)
path_parts := path.split('/').filter(it.len > 0)
for route in r.dynamic_routes {
pattern_parts := route.pattern.split('/').filter(it.len > 0)
if path_parts.len != pattern_parts.len {
continue
}
mut matched := true
mut params := map[string]string{}
mut param_idx := 0
for i, part in pattern_parts {
if part.starts_with(':') {
// 参数匹配
if param_idx < route.param_names.len {
params[route.param_names[param_idx]] = path_parts[i]
param_idx++
}
} else if part != path_parts[i] {
matched = false
break
}
}
if matched {
return true, params
}
}
return false, map[string]string{}
}
// ============================================
// 基准测试函数
// ============================================
struct BenchmarkResult {
name string
total_time_ns i64
avg_time_ns i64
min_time_ns i64
max_time_ns i64
ops_per_sec f64
iterations int
}
fn benchmark(name string, iterations int, f fn () bool) BenchmarkResult {
mut times := []i64{cap: iterations}
mut min_time := i64(9223372036854775807)
mut max_time := i64(0)
// 预热
for _ in 0 .. warmup_iterations {
f()
}
// 正式测试
for _ in 0 .. iterations {
sw := time.new_stopwatch()
f()
elapsed := sw.elapsed().nanoseconds()
times << elapsed
if elapsed < min_time {
min_time = elapsed
}
if elapsed > max_time {
max_time = elapsed
}
}
mut total := i64(0)
for t in times {
total += t
}
avg := total / iterations
ops_per_sec := 1_000_000_000.0 / f64(avg)
return BenchmarkResult{
name: name
total_time_ns: total
avg_time_ns: avg
min_time_ns: min_time
max_time_ns: max_time
ops_per_sec: ops_per_sec
iterations: iterations
}
}
fn print_result(r BenchmarkResult) {
println('┌─────────────────────────────────────────────────────────────┐')
println('│ ${r.name:-59} │')
println('├─────────────────────────────────────────────────────────────┤')
println('│ 迭代次数: ${r.iterations:-48} │')
println('│ 总耗时: ${r.total_time_ns / 1_000_000:-45} ms │')
println('│ 平均耗时: ${r.avg_time_ns:-45} ns │')
println('│ 最小耗时: ${r.min_time_ns:-45} ns │')
println('│ 最大耗时: ${r.max_time_ns:-45} ns │')
println('│ 吞吐量: ${r.ops_per_sec:-42.0} ops/s │')
println('└─────────────────────────────────────────────────────────────┘')
}
fn print_comparison(name string, simple_result BenchmarkResult, hono_result BenchmarkResult) {
speedup := f64(simple_result.avg_time_ns) / f64(hono_result.avg_time_ns)
winner := if speedup > 1.0 { 'v-hono' } else { 'SimpleRouter' }
ratio := if speedup > 1.0 { speedup } else { 1.0 / speedup }
println('')
println('═══════════════════════════════════════════════════════════════')
println(' ${name} 对比结果')
println('═══════════════════════════════════════════════════════════════')
println(' SimpleRouter: ${simple_result.avg_time_ns} ns/op (${simple_result.ops_per_sec:.0} ops/s)')
println(' v-hono: ${hono_result.avg_time_ns} ns/op (${hono_result.ops_per_sec:.0} ops/s)')
println(' 胜出: ${winner} (快 ${ratio:.2}x)')
println('═══════════════════════════════════════════════════════════════')
}
// ============================================
// 主测试函数
// ============================================
fn main() {
println('')
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ veb vs v-hono 路由性能对比测试 ║')
println('║ (SimpleRouter 模拟 veb 的路由匹配方式) ║')
println('╠═══════════════════════════════════════════════════════════════╣')
println('║ 测试配置: ║')
println('║ - 迭代次数: ${iterations:-46} ║')
println('║ - 预热次数: ${warmup_iterations:-46} ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
// 初始化 SimpleRouter
mut simple_router := SimpleRouter.new()
simple_router.add_static('/')
simple_router.add_static('/api/health')
simple_router.add_static('/api/users')
simple_router.add_dynamic('/api/users/:id', ['id'])
simple_router.add_dynamic('/api/users/:id/posts', ['id'])
simple_router.add_dynamic('/api/users/:user_id/posts/:post_id', ['user_id', 'post_id'])
simple_router.add_dynamic('/api/categories/:cat/items/:item', ['cat', 'item'])
// 初始化 v-hono
mut hono_app := hono.Hono.new()
hono_app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello World')
})
hono_app.get('/api/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
hono_app.get('/api/users', fn (mut c hono.Context) http.Response {
return c.json('{"users": []}')
})
hono_app.get('/api/users/:id', fn (mut c hono.Context) http.Response {
return c.json('{"id": "123"}')
})
hono_app.get('/api/users/:id/posts', fn (mut c hono.Context) http.Response {
return c.json('{"posts": []}')
})
hono_app.get('/api/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
return c.json('{"post": {}}')
})
hono_app.get('/api/categories/:cat/items/:item', fn (mut c hono.Context) http.Response {
return c.json('{"item": {}}')
})
// ============================================
// 测试 1: 静态路由性能
// ============================================
println('\n【测试 1】静态路由匹配性能')
println('─────────────────────────────────────────────────────────────────')
simple_static_result := benchmark('SimpleRouter 静态路由', iterations, fn [simple_router] () bool {
for path in static_paths {
simple_router.match_route(path)
}
return true
})
print_result(simple_static_result)
hono_static_result := benchmark('v-hono 静态路由', iterations, fn [mut hono_app] () bool {
for path in static_paths {
hono_app.fast_router.match_route('GET', path) or { continue }
}
return true
})
print_result(hono_static_result)
print_comparison('静态路由', simple_static_result, hono_static_result)
// ============================================
// 测试 2: 动态路由性能
// ============================================
println('\n【测试 2】动态路由匹配性能')
println('─────────────────────────────────────────────────────────────────')
simple_dynamic_result := benchmark('SimpleRouter 动态路由', iterations, fn [simple_router] () bool {
for path in dynamic_paths {
simple_router.match_route(path)
}
return true
})
print_result(simple_dynamic_result)
hono_dynamic_result := benchmark('v-hono 动态路由', iterations, fn [mut hono_app] () bool {
for path in dynamic_paths {
hono_app.fast_router.match_route('GET', path) or { continue }
}
return true
})
print_result(hono_dynamic_result)
print_comparison('动态路由', simple_dynamic_result, hono_dynamic_result)
// ============================================
// 测试 3: 混合路由性能
// ============================================
println('\n【测试 3】混合路由匹配性能(静态 + 动态)')
println('─────────────────────────────────────────────────────────────────')
mut all_paths := []string{}
all_paths << static_paths
all_paths << dynamic_paths
simple_mixed_result := benchmark('SimpleRouter 混合路由', iterations, fn [simple_router, all_paths] () bool {
for path in all_paths {
simple_router.match_route(path)
}
return true
})
print_result(simple_mixed_result)
hono_mixed_result := benchmark('v-hono 混合路由', iterations, fn [mut hono_app, all_paths] () bool {
for path in all_paths {
hono_app.fast_router.match_route('GET', path) or { continue }
}
return true
})
print_result(hono_mixed_result)
print_comparison('混合路由', simple_mixed_result, hono_mixed_result)
// ============================================
// 路由器统计信息
// ============================================
println('\n【路由器统计信息】')
println('─────────────────────────────────────────────────────────────────')
static_count, dynamic_count, cache_count, _ := hono_app.get_router_stats()
println('v-hono FastRouter:')
println(' - 静态路由数: ${static_count}')
println(' - 动态路由数: ${dynamic_count}')
println(' - 缓存条目数: ${cache_count}')
println('')
println('SimpleRouter:')
println(' - 静态路由数: ${simple_router.static_routes.len}')
println(' - 动态路由数: ${simple_router.dynamic_routes.len}')
// ============================================
// 总结
// ============================================
println('\n')
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ 测试总结 ║')
println('╠═══════════════════════════════════════════════════════════════╣')
println('║ 1. 静态路由: SimpleRouter 使用 map 直接查找,通常更快 ║')
println('║ 2. 动态路由: v-hono 使用 Trie + 缓存,性能更稳定 ║')
println('║ 3. v-hono 的优势在于动态路由性能一致,不随复杂度增加而下降 ║')
println('╚═══════════════════════════════════════════════════════════════╝')
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
fn main() {
+237
View File
@@ -0,0 +1,237 @@
// HTTP 压测工具 - veb vs v-hono 性能对比
// 运行: v run http_benchmark.v
//
// 使用前请先启动服务器:
// 终端1: v run server_veb.v (端口 8080)
// 终端2: v run server_hono.v (端口 8081)
module main
import net.http
import time
// 测试配置
const veb_base_url = 'http://127.0.0.1:8080'
const hono_base_url = 'http://127.0.0.1:8081'
const requests_per_endpoint = 200
// 测试端点
struct Endpoint {
path string
name string
}
const test_endpoints = [
Endpoint{path: '/', name: '首页 (静态)'},
Endpoint{path: '/api/health', name: '健康检查 (静态)'},
Endpoint{path: '/api/users', name: '用户列表 (静态)'},
Endpoint{path: '/api/users/123', name: '单个用户 (动态)'},
Endpoint{path: '/api/users/456/posts', name: '用户帖子 (动态)'},
]
struct BenchmarkResult {
endpoint string
total_requests int
success_count int
error_count int
total_time_ms i64
avg_time_ms f64
min_time_ms f64
max_time_ms f64
rps f64
}
fn main() {
println('')
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ HTTP 压测工具 - veb vs v-hono 性能对比 ║')
println('╠═══════════════════════════════════════════════════════════════╣')
println('║ 请确保已启动以下服务器: ║')
println('║ - veb: v run server_veb.v (端口 8080) ║')
println('║ - v-hono: v run server_hono.v (端口 8081) ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
// 检查服务器是否可用
println('检查服务器状态...')
veb_available := check_server(veb_base_url)
hono_available := check_server(hono_base_url)
if !veb_available {
println('⚠️ veb 服务器 (${veb_base_url}) 不可用')
} else {
println('✅ veb 服务器 (${veb_base_url}) 已就绪')
}
if !hono_available {
println('⚠️ v-hono 服务器 (${hono_base_url}) 不可用')
} else {
println('✅ v-hono 服务器 (${hono_base_url}) 已就绪')
}
if !veb_available && !hono_available {
println('')
println('❌ 没有可用的服务器,请先启动服务器后再运行测试')
return
}
println('')
println('开始压测 (每端点 ${requests_per_endpoint} 次请求)...')
println('─────────────────────────────────────────────────────────────────')
mut veb_results := []BenchmarkResult{}
mut hono_results := []BenchmarkResult{}
for endpoint in test_endpoints {
println('')
println('测试端点: ${endpoint.name} (${endpoint.path})')
if veb_available {
result := run_benchmark('veb', veb_base_url, endpoint)
veb_results << result
print_single_result('veb', result)
}
if hono_available {
result := run_benchmark('v-hono', hono_base_url, endpoint)
hono_results << result
print_single_result('v-hono', result)
}
}
// 打印对比结果
if veb_available && hono_available {
print_comparison_table(veb_results, hono_results)
}
// 打印总结
print_summary(veb_results, hono_results, veb_available, hono_available)
}
fn check_server(base_url string) bool {
http.get(base_url) or { return false }
return true
}
fn run_benchmark(name string, base_url string, endpoint Endpoint) BenchmarkResult {
url := '${base_url}${endpoint.path}'
mut success_count := 0
mut error_count := 0
mut min_time := f64(999999.0)
mut max_time := f64(0.0)
mut total_req_time := f64(0.0)
start_time := time.now()
for _ in 0 .. requests_per_endpoint {
req_start := time.now()
resp := http.get(url) or {
error_count++
continue
}
req_time := f64(time.since(req_start).microseconds()) / 1000.0
if resp.status_code >= 200 && resp.status_code < 300 {
success_count++
} else {
error_count++
}
total_req_time += req_time
if req_time < min_time {
min_time = req_time
}
if req_time > max_time {
max_time = req_time
}
}
total_time := time.since(start_time)
total_time_ms := total_time.milliseconds()
total_requests := success_count + error_count
avg_time := if total_requests > 0 { total_req_time / f64(total_requests) } else { 0.0 }
rps := if total_time_ms > 0 { f64(total_requests) * 1000.0 / f64(total_time_ms) } else { 0.0 }
return BenchmarkResult{
endpoint: endpoint.name
total_requests: total_requests
success_count: success_count
error_count: error_count
total_time_ms: total_time_ms
avg_time_ms: avg_time
min_time_ms: min_time
max_time_ms: max_time
rps: rps
}
}
fn print_single_result(name string, r BenchmarkResult) {
println(' ${name}: ${r.rps:.0} req/s | avg: ${r.avg_time_ms:.2}ms | min: ${r.min_time_ms:.2}ms | max: ${r.max_time_ms:.2}ms | 成功: ${r.success_count}/${r.total_requests}')
}
fn print_comparison_table(veb_results []BenchmarkResult, hono_results []BenchmarkResult) {
println('')
println('╔═══════════════════════════════════════════════════════════════════════════════════════╗')
println('║ 性能对比表 ║')
println('╠═══════════════════════════════════════════════════════════════════════════════════════╣')
println('║ 端点 │ veb (req/s) │ v-hono (req/s) │ 差异 │ 胜出 ║')
println('╠═══════════════════════════════════════════════════════════════════════════════════════╣')
for i, veb_r in veb_results {
if i >= hono_results.len {
break
}
hono_r := hono_results[i]
diff := hono_r.rps - veb_r.rps
diff_pct := if veb_r.rps > 0 { (diff / veb_r.rps) * 100.0 } else { 0.0 }
winner := if hono_r.rps > veb_r.rps { 'v-hono' } else { 'veb' }
name := veb_r.endpoint
veb_rps := '${veb_r.rps:.0}'
hono_rps := '${hono_r.rps:.0}'
diff_str := if diff > 0 { '+${diff_pct:.1}%' } else { '${diff_pct:.1}%' }
println('║ ${name:-23} │ ${veb_rps:-12} │ ${hono_rps:-14} │ ${diff_str:-9} │ ${winner:-14} ║')
}
println('╚═══════════════════════════════════════════════════════════════════════════════════════╝')
}
fn print_summary(veb_results []BenchmarkResult, hono_results []BenchmarkResult, veb_available bool, hono_available bool) {
println('')
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ 测试总结 ║')
println('╠═══════════════════════════════════════════════════════════════╣')
if veb_available && veb_results.len > 0 {
mut total_rps := f64(0.0)
for r in veb_results {
total_rps += r.rps
}
avg_rps := total_rps / f64(veb_results.len)
println('║ veb 平均吞吐量: ${avg_rps:-40.0} req/s ║')
}
if hono_available && hono_results.len > 0 {
mut total_rps := f64(0.0)
for r in hono_results {
total_rps += r.rps
}
avg_rps := total_rps / f64(hono_results.len)
println('║ v-hono 平均吞吐量: ${avg_rps:-40.0} req/s ║')
}
println('╠═══════════════════════════════════════════════════════════════╣')
println('║ 测试配置: ║')
println('║ - 每端点请求数: ${requests_per_endpoint:-44} ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
println('提示: 使用 wrk 或 ab 可以获得更准确的压测结果:')
println(' wrk -t4 -c100 -d10s http://127.0.0.1:8080/')
println(' wrk -t4 -c100 -d10s http://127.0.0.1:8081/')
}
+2 -2
View File
@@ -3,7 +3,7 @@ module main
import net.http
import time
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -34,6 +34,6 @@ fn main() {
return c.json('{"data": "some data"}')
})
println('Server starting on http://localhost:3000')
println('Server starting on http://127.0.0.1:3000')
app.listen(':3000')
}
+24
View File
@@ -0,0 +1,24 @@
module main
import net.http
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello from V-Hono + picoev!')
})
app.get('/json', fn (mut c hono.Context) http.Response {
return c.json('{"message": "Hello, JSON!"}')
})
app.get('/users/:id', fn (mut c hono.Context) http.Response {
user_id := c.params['id'] or { 'unknown' }
return c.json('{"user_id": "${user_id}"}')
})
// 使用默认 picoev 后端
app.listen(':3009')
}
+75
View File
@@ -0,0 +1,75 @@
module main
import meiseayoung.hono
import net.http
fn main() {
mut app := hono.Hono.new()
// Basic redirect (302 Found)
app.get('/redirect-basic', fn (mut c hono.Context) http.Response {
return c.redirect('https://example.com')
})
// Redirect with custom status code (301 Moved Permanently)
app.get('/redirect-permanent', fn (mut c hono.Context) http.Response {
return c.redirect('https://example.com', 301)
})
// Redirect with 303 See Other
app.post('/form-submit', fn (mut c hono.Context) http.Response {
// Process form data here...
// Then redirect to success page
return c.redirect('/success', 303)
})
// Redirect with 307 Temporary Redirect (preserves method)
app.get('/redirect-preserve-method', fn (mut c hono.Context) http.Response {
return c.redirect('/new-location', 307)
})
// Redirect with 308 Permanent Redirect (preserves method)
app.get('/redirect-permanent-preserve', fn (mut c hono.Context) http.Response {
return c.redirect('/new-permanent-location', 308)
})
// Conditional redirect
app.get('/conditional-redirect', fn (mut c hono.Context) http.Response {
user_agent := c.req.header.get_custom('User-Agent') or { '' }
if user_agent.contains('Mobile') {
return c.redirect('/mobile-version')
} else {
return c.redirect('/desktop-version')
}
})
// Redirect to relative path
app.get('/relative-redirect', fn (mut c hono.Context) http.Response {
return c.redirect('../other-page')
})
// Success page for demonstration
app.get('/success', fn (mut c hono.Context) http.Response {
return c.html('<h1>Success!</h1><p>Form submitted successfully.</p>')
})
app.get('/mobile-version', fn (mut c hono.Context) http.Response {
return c.html('<h1>Mobile Version</h1>')
})
app.get('/desktop-version', fn (mut c hono.Context) http.Response {
return c.html('<h1>Desktop Version</h1>')
})
println('Server running on http://127.0.0.1:8080')
println('Try these endpoints:')
println(' GET /redirect-basic - Basic redirect (302)')
println(' GET /redirect-permanent - Permanent redirect (301)')
println(' POST /form-submit - Form redirect (303)')
println(' GET /redirect-preserve-method - Temporary redirect preserving method (307)')
println(' GET /conditional-redirect - Conditional redirect based on User-Agent')
println(' GET /relative-redirect - Relative path redirect')
app.listen(':8080')
}
+2 -2
View File
@@ -2,7 +2,7 @@
module main
import net.http
import hono
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
@@ -31,7 +31,7 @@ fn main() {
return c.html('<h1>Welcome to v-hono!</h1><p>API available at /api</p>')
})
println('Server starting on http://localhost:3000')
println('Server starting on http://127.0.0.1:3000')
println('Routes:')
println(' GET / - Welcome page')
println(' GET /api/users - List users')
@@ -12,7 +12,7 @@
// ```
import net.http
import hono
import meiseayoung.hono
fn main() {
println('🚀 V-Hono 路由分组示例启动中...')
@@ -211,7 +211,7 @@ app.route("/api/books", mut books)</pre>
// 打印路由信息
fn print_routes_info() {
println('')
println('📍 服务器地址: http://localhost:8080')
println('📍 服务器地址: http://127.0.0.1:8080')
println('')
println('📚 Books API (/api/books):')
println(' GET /api/books - 获取所有书籍')
@@ -2,7 +2,7 @@
// 演示新功能:子应用中间件继承、all() 方法、notFound/onError 处理器
import net.http
import hono
import meiseayoung.hono
fn main() {
println('🚀 V-Hono 路由分组增强示例启动中...')
@@ -233,16 +233,16 @@ app.route(\'/api/books\', mut books)</pre>
<div class="group">
<h2>🧪 测试命令</h2>
<pre># 测试 all() 方法
curl http://localhost:8080/echo
curl -X POST http://localhost:8080/echo
curl -X PUT http://localhost:8080/echo
curl http://127.0.0.1:8080/echo
curl -X POST http://127.0.0.1:8080/echo
curl -X PUT http://127.0.0.1:8080/echo
# 测试自定义 404
curl http://localhost:8080/not-exist
curl http://127.0.0.1:8080/not-exist
# 测试 Admin 认证中间件
curl http://localhost:8080/admin # 返回 401
curl -H "Authorization: Bearer admin-token" http://localhost:8080/admin # 成功</pre>
curl http://127.0.0.1:8080/admin # 返回 401
curl -H "Authorization: Bearer admin-token" http://127.0.0.1:8080/admin # 成功</pre>
</div>
</body>
</html>'
@@ -251,7 +251,7 @@ curl -H "Authorization: Bearer admin-token" http://localhost:8080/admin # 成
// 打印路由信息
fn print_routes_info() {
println('')
println('📍 服务器地址: http://localhost:8080')
println('📍 服务器地址: http://127.0.0.1:8080')
println('')
println('🆕 新功能:')
println(' - notFound(): 自定义 404 处理器')
+82
View File
@@ -0,0 +1,82 @@
# veb vs v-hono 性能对比测试脚本
# 运行: .\run_benchmark.ps1
Write-Host ""
Write-Host "╔═══════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║ veb vs v-hono 性能对比测试 ║" -ForegroundColor Cyan
Write-Host "╚═══════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
Write-Host ""
# 检查 V 编译器
if (-not (Get-Command v -ErrorAction SilentlyContinue)) {
Write-Host "❌ 未找到 V 编译器,请先安装 V 语言" -ForegroundColor Red
exit 1
}
Write-Host "✅ V 编译器已安装" -ForegroundColor Green
Write-Host ""
# 菜单
Write-Host "请选择测试类型:" -ForegroundColor Yellow
Write-Host " 1. 路由匹配性能测试 (不需要启动服务器)"
Write-Host " 2. HTTP 压测 (需要先启动服务器)"
Write-Host " 3. 启动 veb 服务器 (端口 8080)"
Write-Host " 4. 启动 v-hono 服务器 (端口 8081)"
Write-Host " 5. 编译所有测试文件"
Write-Host " 6. 退出"
Write-Host ""
$choice = Read-Host "请输入选项 (1-6)"
switch ($choice) {
"1" {
Write-Host ""
Write-Host "运行路由匹配性能测试..." -ForegroundColor Cyan
v run benchmark_veb_vs_hono.v
}
"2" {
Write-Host ""
Write-Host "运行 HTTP 压测..." -ForegroundColor Cyan
Write-Host "请确保已在其他终端启动服务器:" -ForegroundColor Yellow
Write-Host " - veb: v run server_veb.v (端口 8080)"
Write-Host " - v-hono: v run server_hono.v (端口 8081)"
Write-Host ""
v run http_benchmark.v
}
"3" {
Write-Host ""
Write-Host "启动 veb 服务器 (端口 8080)..." -ForegroundColor Cyan
v run server_veb.v
}
"4" {
Write-Host ""
Write-Host "启动 v-hono 服务器 (端口 8081)..." -ForegroundColor Cyan
v run server_hono.v
}
"5" {
Write-Host ""
Write-Host "编译所有测试文件..." -ForegroundColor Cyan
Write-Host "编译 benchmark_veb_vs_hono.v..."
v -prod benchmark_veb_vs_hono.v -o benchmark_veb_vs_hono.exe
Write-Host "编译 server_veb.v..."
v -prod server_veb.v -o server_veb.exe
Write-Host "编译 server_hono.v..."
v -prod server_hono.v -o server_hono.exe
Write-Host "编译 http_benchmark.v..."
v -prod http_benchmark.v -o http_benchmark.exe
Write-Host ""
Write-Host "✅ 编译完成!" -ForegroundColor Green
}
"6" {
Write-Host "退出" -ForegroundColor Yellow
exit 0
}
default {
Write-Host "无效选项" -ForegroundColor Red
}
}
+2 -2
View File
@@ -1,10 +1,10 @@
// v-hono 服务器示例 - 用于性能对比测试
// 运行: v run server_hono.v
// 测试: curl http://localhost:8081/
// 测试: curl http://127.0.0.1:8081/
module main
import hono
import meiseayoung.hono
import net.http
fn main() {
+61
View File
@@ -0,0 +1,61 @@
// v-hono picoev 服务器示例 - 高性能版本
// 运行: v run server_hono_picoev.v
// 测试: curl http://127.0.0.1:8081/
module main
import meiseayoung.hono
import net.http
fn main() {
mut app := hono.Hono.new()
// 静态路由
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello World')
})
app.get('/api/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
app.get('/api/users', fn (mut c hono.Context) http.Response {
return c.json('{"users": []}')
})
app.post('/api/users', fn (mut c hono.Context) http.Response {
return c.json('{"created": true}')
})
// 动态路由
app.get('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}"}')
})
app.get('/api/users/:id/posts', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"posts": [], "user_id": "${id}"}')
})
app.get('/api/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
user_id := c.params['user_id'] or { '' }
post_id := c.params['post_id'] or { '' }
return c.json('{"user_id": "${user_id}", "post_id": "${post_id}"}')
})
app.get('/api/categories/:cat/items/:item', fn (mut c hono.Context) http.Response {
cat := c.params['cat'] or { '' }
item := c.params['item'] or { '' }
return c.json('{"category": "${cat}", "item": "${item}"}')
})
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ v-hono picoev 服务器 - 高性能版本 ║')
println('╠═══════════════════════════════════════════════════════════════╣')
println('║ 端口: 8081 ║')
println('║ 特性: picoev 事件驱动 + Keep-Alive ║')
println('╚═══════════════════════════════════════════════════════════════╝')
app.listen_picoev(8081)
}
+164
View File
@@ -0,0 +1,164 @@
// veb 服务器示例 - 用于性能对比测试
// veb 是 V 语言官方的新版 web 框架(替代旧的 vweb)
//
// 运行: v run server_veb.v
// 测试: curl http://127.0.0.1:8080/
//
// 压测命令:
// wrk -t4 -c100 -d10s http://127.0.0.1:8080/
// wrk -t4 -c100 -d10s http://127.0.0.1:8080/api/users/123
module main
import veb
import time
// 应用状态
pub struct App {
pub:
start_time time.Time = time.now()
}
// Context 类型
pub struct Context {
veb.Context
}
fn main() {
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ veb 服务器 - 性能对比测试 ║')
println('╠═══════════════════════════════════════════════════════════════╣')
println('║ 端口: 8080 ║')
println('║ 测试端点: ║')
println('║ GET / - Hello World ║')
println('║ GET /api/health - 健康检查 ║')
println('║ GET /api/users - 获取用户列表 ║')
println('║ POST /api/users - 创建用户 ║')
println('║ GET /api/users/:id - 获取单个用户 ║')
println('║ GET /api/users/:id/posts - 获取用户帖子 ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
println('启动 veb 服务器在端口 8080...')
mut app := &App{}
veb.run[App, Context](mut app, 8080)
}
// ============================================
// 静态路由
// ============================================
// 首页
@['/']
pub fn (app &App) index(mut ctx Context) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.text('Hello World')
}
// 健康检查
@['/api/health']
pub fn (app &App) health(mut ctx Context) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.text('OK')
}
// 获取用户列表
@['/api/users'; get]
pub fn (app &App) get_users(mut ctx Context) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.json[[]User]([
User{id: '1', name: 'Alice', email: 'alice@example.com'},
User{id: '2', name: 'Bob', email: 'bob@example.com'},
])
}
// 创建用户
@['/api/users'; post]
pub fn (app &App) create_user(mut ctx Context) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.json[CreateResponse](CreateResponse{created: true, id: '3'})
}
// ============================================
// 动态路由
// ============================================
// 获取单个用户
@['/api/users/:id']
pub fn (app &App) get_user(mut ctx Context, id string) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.json[User](User{id: id, name: 'User ${id}', email: 'user${id}@example.com'})
}
// 获取用户的帖子
@['/api/users/:id/posts']
pub fn (app &App) get_user_posts(mut ctx Context, id string) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.json[PostsResponse](PostsResponse{
user_id: id
posts: [
Post{id: '1', title: 'First Post', content: 'Hello World'},
Post{id: '2', title: 'Second Post', content: 'V is awesome'},
]
})
}
// 获取特定帖子
@['/api/users/:user_id/posts/:post_id']
pub fn (app &App) get_user_post(mut ctx Context, user_id string, post_id string) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.json[PostResponse](PostResponse{
user_id: user_id
post_id: post_id
post: Post{id: post_id, title: 'Post ${post_id}', content: 'Content of post ${post_id}'}
})
}
// 获取分类商品
@['/api/categories/:cat/items/:item']
pub fn (app &App) get_category_item(mut ctx Context, cat string, item string) veb.Result {
ctx.set_header(.connection, 'close')
return ctx.json[ItemResponse](ItemResponse{
category: cat
item: item
price: 99.99
})
}
// ============================================
// 数据结构
// ============================================
struct User {
id string
name string
email string
}
struct Post {
id string
title string
content string
}
struct CreateResponse {
created bool
id string
}
struct PostsResponse {
user_id string
posts []Post
}
struct PostResponse {
user_id string
post_id string
post Post
}
struct ItemResponse {
category string
item string
price f64
}
+1 -1
View File
@@ -1,6 +1,6 @@
// vweb 服务器示例 - 用于性能对比测试
// 运行: v run server_vweb.v
// 测试: curl http://localhost:8080/
// 测试: curl http://127.0.0.1:8080/
module main
+93
View File
@@ -0,0 +1,93 @@
// 简单 HTTP 压测 - veb vs v-hono
// v run simple_benchmark.v
module main
import net.http
import time
const requests = 50
fn main() {
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ 简单 HTTP 压测 - veb vs v-hono ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
// 测试 veb
println('测试 veb (http://127.0.0.1:8080/)...')
veb_result := benchmark_server('http://127.0.0.1:8080/')
println(' 结果: ${veb_result.rps:.0} req/s | avg: ${veb_result.avg_ms:.2}ms | 成功: ${veb_result.success}/${veb_result.total}')
// 测试 v-hono
println('')
println('测试 v-hono (http://127.0.0.1:8081/)...')
hono_result := benchmark_server('http://127.0.0.1:8081/')
println(' 结果: ${hono_result.rps:.0} req/s | avg: ${hono_result.avg_ms:.2}ms | 成功: ${hono_result.success}/${hono_result.total}')
// 对比
println('')
println('═══════════════════════════════════════════════════════════════')
if veb_result.rps > 0 && hono_result.rps > 0 {
if hono_result.rps > veb_result.rps {
ratio := hono_result.rps / veb_result.rps
println('v-hono 快 ${ratio:.2}x')
} else {
ratio := veb_result.rps / hono_result.rps
println('veb 快 ${ratio:.2}x')
}
}
println('═══════════════════════════════════════════════════════════════')
}
struct Result {
total int
success int
rps f64
avg_ms f64
}
fn benchmark_server(url string) Result {
// 先检查服务器
http.get(url) or {
println(' ⚠️ 服务器不可用')
return Result{}
}
mut success := 0
mut total_ms := f64(0)
start := time.now()
for i in 0 .. requests {
req_start := time.now()
resp := http.get(url) or {
continue
}
req_ms := f64(time.since(req_start).microseconds()) / 1000.0
if resp.status_code == 200 {
success++
}
total_ms += req_ms
// 进度
if (i + 1) % 10 == 0 {
print('.')
}
}
println('')
elapsed := time.since(start)
elapsed_ms := elapsed.milliseconds()
rps := if elapsed_ms > 0 { f64(requests) * 1000.0 / f64(elapsed_ms) } else { 0.0 }
avg_ms := if requests > 0 { total_ms / f64(requests) } else { 0.0 }
return Result{
total: requests
success: success
rps: rps
avg_ms: avg_ms
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import os
+13 -13
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import os
import time
@@ -21,7 +21,7 @@ fn main() {
// 等待服务器启动
time.sleep(2 * time.second)
println('服务器已启动在 http://localhost:8081')
println('服务器已启动在 http://127.0.0.1:8081')
// 执行测试
run_tests()
@@ -124,7 +124,7 @@ fn test_small_file_performance() {
// 传统方式
start := time.now()
for i in 0 .. 100 {
_ = os.execute('curl -s http://localhost:8081/traditional/test_small.txt > nul')
_ = os.execute('curl -s http://127.0.0.1:8081/traditional/test_small.txt > nul')
}
traditional_time := time.now() - start
println('传统方式 100次请求: $traditional_time')
@@ -132,7 +132,7 @@ fn test_small_file_performance() {
// 流式方式
start2 := time.now()
for i in 0 .. 100 {
_ = os.execute('curl -s http://localhost:8081/stream/test_small.txt > nul')
_ = os.execute('curl -s http://127.0.0.1:8081/stream/test_small.txt > nul')
}
stream_time := time.now() - start2
println('流式方式 100次请求: $stream_time')
@@ -140,7 +140,7 @@ fn test_small_file_performance() {
// 智能方式
start3 := time.now()
for i in 0 .. 100 {
_ = os.execute('curl -s http://localhost:8081/smart/test_small.txt > nul')
_ = os.execute('curl -s http://127.0.0.1:8081/smart/test_small.txt > nul')
}
smart_time := time.now() - start3
println('智能方式 100次请求: $smart_time')
@@ -152,7 +152,7 @@ fn test_medium_file_performance() {
// 传统方式
start := time.now()
for i in 0 .. 10 {
_ = os.execute('curl -s http://localhost:8081/traditional/test_medium.txt > nul')
_ = os.execute('curl -s http://127.0.0.1:8081/traditional/test_medium.txt > nul')
}
traditional_time := time.now() - start
println('传统方式 10次请求: $traditional_time')
@@ -160,7 +160,7 @@ fn test_medium_file_performance() {
// 流式方式
start2 := time.now()
for i in 0 .. 10 {
_ = os.execute('curl -s http://localhost:8081/stream/test_medium.txt > nul')
_ = os.execute('curl -s http://127.0.0.1:8081/stream/test_medium.txt > nul')
}
stream_time := time.now() - start2
println('流式方式 10次请求: $stream_time')
@@ -172,7 +172,7 @@ fn test_large_file_performance() {
// 只测试流式方式,避免内存问题
start := time.now()
for i in 0 .. 5 {
result := os.execute('curl -s http://localhost:8081/stream/test_large.txt > nul')
result := os.execute('curl -s http://127.0.0.1:8081/stream/test_large.txt > nul')
if result.exit_code != 0 {
println(' 请求 $i 失败')
}
@@ -183,7 +183,7 @@ fn test_large_file_performance() {
// 智能方式(应该自动选择流式传输)
start2 := time.now()
for i in 0 .. 5 {
result := os.execute('curl -s http://localhost:8081/smart/test_large.txt > nul')
result := os.execute('curl -s http://127.0.0.1:8081/smart/test_large.txt > nul')
if result.exit_code != 0 {
println(' 智能方式请求 $i 失败')
}
@@ -196,14 +196,14 @@ fn test_range_requests() {
println('\n--- Range请求测试 ---')
// 测试部分内容请求
result1 := os.execute('curl -s -H "Range: bytes=0-99" http://localhost:8081/range/test_medium.txt')
result1 := os.execute('curl -s -H "Range: bytes=0-99" http://127.0.0.1:8081/range/test_medium.txt')
if result1.exit_code == 0 {
println('✅ Range请求 0-99: 成功')
} else {
println('❌ Range请求 0-99: 失败')
}
result2 := os.execute('curl -s -H "Range: bytes=100-199" http://localhost:8081/range/test_medium.txt')
result2 := os.execute('curl -s -H "Range: bytes=100-199" http://127.0.0.1:8081/range/test_medium.txt')
if result2.exit_code == 0 {
println('✅ Range请求 100-199: 成功')
} else {
@@ -215,7 +215,7 @@ fn test_smart_selection() {
println('\n--- 智能选择测试 ---')
// 测试小文件(应该使用内存加载)
result1 := os.execute('curl -s http://localhost:8081/smart/test_small.txt')
result1 := os.execute('curl -s http://127.0.0.1:8081/smart/test_small.txt')
if result1.exit_code == 0 {
println('✅ 智能选择小文件: 成功')
} else {
@@ -223,7 +223,7 @@ fn test_smart_selection() {
}
// 测试大文件(应该使用流式传输)
result2 := os.execute('curl -s -o large_output.txt http://localhost:8081/smart/test_large.txt')
result2 := os.execute('curl -s -o large_output.txt http://127.0.0.1:8081/smart/test_large.txt')
if result2.exit_code == 0 {
// 检查下载的文件大小
if os.exists('large_output.txt') {
+24
View File
@@ -0,0 +1,24 @@
// 测试服务器 - 用于高并发测试
module main
import meiseayoung.hono
import net.http
fn main() {
mut app := hono.Hono.new()
// 简单的测试路由
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
app.get('/delay', fn (mut c hono.Context) http.Response {
// 模拟一些处理延迟
return c.text('OK with delay')
})
println('测试服务器启动中...')
println('配置: timeout_secs=120, keepalive_timeout=30, max_keepalive_req=10000')
app.listen(':8888')
}
+24
View File
@@ -0,0 +1,24 @@
module main
import net.http
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello from V-Hono + uSockets!')
})
app.get('/json', fn (mut c hono.Context) http.Response {
return c.json('{"message": "Hello, JSON!"}')
})
app.get('/users/:id', fn (mut c hono.Context) http.Response {
user_id := c.params['id'] or { 'unknown' }
return c.json('{"user_id": "${user_id}"}')
})
// 使用 uSockets 后端
app.listen_usockets(3008)
}
+25 -10
View File
@@ -27,10 +27,12 @@ pub mut:
static_routes map[string]IHandler
static_route_results map[string]ContextRouteMatch // 预分配的静态路由结果
precompiled_routes []PrecompiledRoute
lru_cache ContextLRUCache // 使用 LRU 缓存替代简单 map
fast_cache FastRouteCache // 使用高性能缓存替代 LRU
lru_cache ContextLRUCache // 保留 LRU 缓存用于兼容
regex_cache map[string]FastCompiledRegex // 正则表达式缓存
cache_enabled bool = true
sort_enabled bool = true // 是否启用路由排序
use_fast_cache bool = true // 是否使用高性能缓存
}
// 创建快速路由器
@@ -39,8 +41,10 @@ pub fn FastRouter.new() FastRouter {
static_routes: map[string]IHandler{}
static_route_results: map[string]ContextRouteMatch{}
precompiled_routes: []PrecompiledRoute{}
lru_cache: ContextLRUCache.new(1000) // 默认1000条缓存
fast_cache: FastRouteCache.new(10000) // 高性能缓存,10000条
lru_cache: ContextLRUCache.new(1000) // LRU 缓存保留兼容
regex_cache: map[string]FastCompiledRegex{}
use_fast_cache: true
}
}
@@ -50,8 +54,10 @@ pub fn FastRouter.new_with_cache_size(cache_size int) FastRouter {
static_routes: map[string]IHandler{}
static_route_results: map[string]ContextRouteMatch{}
precompiled_routes: []PrecompiledRoute{}
fast_cache: FastRouteCache.new(cache_size * 10) // 高性能缓存
lru_cache: ContextLRUCache.new(cache_size)
regex_cache: map[string]FastCompiledRegex{}
use_fast_cache: true
}
}
@@ -171,17 +177,23 @@ fn (router FastRouter) precompile_route(method string, handler IHandler) !Precom
}
}
// 快速路由匹配(优化版:静态路由跳过缓存 + 预分配结果)
// 快速路由匹配(优化版:静态路由跳过缓存 + 预分配结果 + 高性能缓存)
pub fn (mut router FastRouter) match_route(method string, path string) ?ContextRouteMatch {
// 优化:只拼接一次 cache key,复用于静态路由和缓存查找
cache_key := '${method}:${path}'
// 1. 静态路由直接返回预分配的结果(零分配)
static_key := '${method}:${path}'
if result := router.static_route_results[static_key] {
if result := router.static_route_results[cache_key] {
return result
}
// 2. 动态路由先检查 LRU 缓存(避免重复正则匹配)
if router.cache_enabled {
cache_key := '${method}:${path}'
// 2. 动态路由先检查高性能缓存(零开销查找)
if router.cache_enabled && router.use_fast_cache {
if cached := router.fast_cache.get(cache_key) {
return cached
}
} else if router.cache_enabled {
// 回退到 LRU 缓存
if cached := router.lru_cache.get(cache_key) {
return cached
}
@@ -208,11 +220,14 @@ pub fn (mut router FastRouter) match_route(method string, path string) ?ContextR
base_path: ''
}
// 只缓存动态路由结果
// 缓存动态路由结果
if router.cache_enabled {
cache_key := '${method}:${path}'
if router.use_fast_cache {
router.fast_cache.put(cache_key, result)
} else {
router.lru_cache.put(cache_key, result)
}
}
return result
}
-154
View File
@@ -1,154 +0,0 @@
module hono
// 简单的 JSON 解析器
pub struct JsonParser {
pub:
data string
}
// 创建 JSON 解析器
pub fn new_json_parser(data string) JsonParser {
return JsonParser{data: data}
}
// 解析 JSON 对象
pub fn (parser JsonParser) parse_object() !map[string]string {
mut result := map[string]string{}
// 移除外层的大括号
data := parser.data.trim_space()
if !data.starts_with('{') || !data.ends_with('}') {
return error('Invalid JSON object format')
}
content := data[1..data.len - 1]
// 分割键值对
pairs := split_json_pairs(content)
for pair in pairs {
key_value := split_key_value(pair) or { continue }
result[key_value.key] = key_value.value
}
return result
}
// 键值对结构
struct KeyValue {
pub:
key string
value string
}
// 分割 JSON 键值对
fn split_json_pairs(content string) []string {
mut pairs := []string{}
mut current := ''
mut brace_count := 0
mut in_string := false
mut escape_next := false
for i := 0; i < content.len; i++ {
ch := content[i]
if escape_next {
current += ch.str()
escape_next = false
continue
}
if ch == `\\` {
escape_next = true
current += ch.str()
continue
}
if ch == `"` && !escape_next {
in_string = !in_string
current += ch.str()
continue
}
if !in_string {
if ch == `{` {
brace_count++
} else if ch == `}` {
brace_count--
} else if ch == `,` && brace_count == 0 {
pairs << current.trim_space()
current = ''
continue
}
}
current += ch.str()
}
if current.trim_space() != '' {
pairs << current.trim_space()
}
return pairs
}
// 分割键值对
fn split_key_value(pair string) !KeyValue {
colon_index := pair.index(':') or {
return error('No colon found')
}
mut key := pair[..colon_index].trim_space()
mut value := pair[colon_index + 1..].trim_space()
// 移除键的引号
if key.starts_with('"') && key.ends_with('"') {
key = key[1..key.len - 1]
}
// 移除值的引号
if value.starts_with('"') && value.ends_with('"') {
value = value[1..value.len - 1]
}
return KeyValue{key: key, value: value}
}
pub struct MergeRequest {
pub:
file_hash string
filename string
total_chunks int
}
// 解析合并请求
pub fn parse_merge_request(body string) !MergeRequest {
if body.len == 0 {
return error('Empty request body')
}
parser := new_json_parser(body)
obj := parser.parse_object() or {
return error('Failed to parse JSON')
}
file_hash := obj['file_hash'] or {
return error('Missing file_hash')
}
filename := obj['filename'] or {
return error('Missing filename')
}
total_chunks_str := obj['total_chunks'] or {
return error('Missing total_chunks')
}
if !total_chunks_str.is_int() {
return error('Invalid total_chunks')
}
total_chunks := total_chunks_str.int()
return MergeRequest{
file_hash: file_hash
filename: filename
total_chunks: total_chunks
}
}
+441
View File
@@ -0,0 +1,441 @@
module hono
import net
import net.http
import picoev
import picohttpparser
// picoev 服务器配置
pub struct PicoevConfig {
pub:
port int = 8080
host string
family net.AddrFamily = .ip6
timeout_secs int = 120 // 高并发场景需要更长超时(原 8 秒太短)
max_headers int = 100
max_read int = 8192
max_write int = 65536
keepalive_timeout int = 30 // Keep-Alive 超时延长到 30 秒
max_keepalive_req int = 10000 // 单连接最大请求数提升到 10000
}
// picoev 请求上下文
struct PicoevRequestContext {
mut:
app &Hono = unsafe { nil }
config PicoevConfig
}
// 使用 picoev 启动服务器
pub fn (mut app Hono) listen_picoev(port int) {
app.listen_picoev_with_config(PicoevConfig{
port: port
})
}
// 使用 picoev 启动服务器(带配置)
pub fn (mut app Hono) listen_picoev_with_config(config PicoevConfig) {
mut ctx := &PicoevRequestContext{
app: unsafe { &app }
config: config
}
mut pico := picoev.new(
port: config.port
host: config.host
family: config.family
timeout_secs: config.timeout_secs
max_headers: config.max_headers
max_read: config.max_read
max_write: config.max_write
cb: picoev_callback
user_data: ctx
) or {
eprintln('[v-hono] Failed to create picoev server: ${err}')
return
}
host_str := if config.host == '' { '127.0.0.1' } else { config.host }
println('[v-hono] Listening on http://${host_str}:${config.port}/ (picoev)')
pico.serve()
}
// picoev 回调函数
fn picoev_callback(user_data voidptr, req picohttpparser.Request, mut res picohttpparser.Response) {
mut ctx := unsafe { &PicoevRequestContext(user_data) }
if ctx.app == unsafe { nil } {
res.http_500()
res.end()
return
}
path, query_map := parse_path_and_query(req.path)
keepalive := check_keepalive_request(req)
method_str := req.method
// 优先使用快速路由器
if ctx.app.use_fast_router {
if route_match := ctx.app.fast_router.match_route(method_str, path) {
mut hono_ctx := create_picoev_context(req, route_match.params, query_map)
// 优化:零中间件快速路径
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)
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
return
}
}
// 回退到混合路由器
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)
// 优化:零中间件快速路径
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)
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
return
}
// 404 Not Found
mut hono_ctx := create_picoev_context(req, map[string]string{}, query_map)
if handler := ctx.app.not_found_handler {
response := handler(mut hono_ctx)
send_picoev_response(mut res, hono_ctx, response, keepalive, ctx.config)
return
}
// 默认 404 响应
res.raw('HTTP/1.1 404 Not Found\r\n')
res.header('Content-Type', 'text/plain')
res.header('Content-Length', '9')
if keepalive {
res.header('Connection', 'keep-alive')
res.header('Keep-Alive', 'timeout=${ctx.config.keepalive_timeout}, max=${ctx.config.max_keepalive_req}')
} else {
res.header('Connection', 'close')
}
res.body('Not Found')
res.end()
}
// 检查客户端是否请求 Keep-Alive - 优化版
// 避免 to_lower() 创建新字符串,使用大小写不敏感比较
fn check_keepalive_request(req picohttpparser.Request) bool {
for i in 0 .. req.num_headers {
h := req.headers[i]
// 大小写不敏感比较 "connection"
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
}
// 大小写不敏感字符串比较(避免分配)
@[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()
// 优化:使用预排序的前缀列表(启动时已排序,不需要每次请求都排序)
for prefix in app.sorted_middleware_prefixes {
if path.starts_with(prefix) || prefix == '/' {
if mws := app.route_middlewares[prefix] {
middlewares << mws
}
}
}
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 {
if idx < middlewares.len {
mw := middlewares[idx]
return mw(mut ctx, fn [idx, middlewares, handler] (mut c Context) http.Response {
return exec_middlewares_picoev(idx + 1, middlewares, mut c, handler)
})
}
return handler.handle(mut ctx)
}
// 解析路径和查询参数 - 零分配优化版
// 使用指针遍历避免创建临时数组
fn parse_path_and_query(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
}
// 快速路径:大多数请求没有查询参数
// 从后向前搜索 '?' 通常更快(查询参数在末尾)
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 {
// 提取纯路径(不含查询参数)
path := extract_path_only(req.path)
return Context{
req: convert_picoev_request(req)
params: params
query: query
body: req.body
url: req.path
path: path
status_code: 200
headers: map[string]string{}
}
}
// 快速提取路径(不含查询参数)
@[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 {
mut headers := http.new_header()
for i in 0 .. req.num_headers {
h := req.headers[i]
headers.add_custom(h.name, h.value) or { continue }
}
return http.Request{
method: parse_http_method_fast(req.method)
url: req.path
data: req.body
header: headers
}
}
// 快速 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) {
status_code := if ctx.status_code != 0 { ctx.status_code } else { response.status_code }
if status_code == 200 {
res.http_ok()
} else {
res.raw('HTTP/1.1 ${status_code} ${get_status_text(status_code)}\r\n')
}
mut has_content_type := false
mut has_connection := false
for key, value in ctx.headers {
// 使用快速大小写不敏感比较
key_len := key.len
if key_len == 14 && eq_ignore_case(key, 'content-length') {
continue // 跳过 Content-Length
}
res.header(key, value)
if key_len == 12 && eq_ignore_case(key, 'content-type') {
has_content_type = true
} else if key_len == 10 && eq_ignore_case(key, 'connection') {
has_connection = true
}
}
if !has_content_type {
if content_type := response.header.get(.content_type) {
res.header('Content-Type', content_type)
has_content_type = true
}
}
if !has_content_type {
res.header('Content-Type', 'text/plain; charset=utf-8')
}
if !has_connection {
if keepalive {
res.header('Connection', 'keep-alive')
res.header('Keep-Alive', 'timeout=${config.keepalive_timeout}, max=${config.max_keepalive_req}')
} else {
res.header('Connection', 'close')
}
}
res.body(response.body)
res.end()
}
// 获取状态码文本
fn get_status_text(code int) string {
return match code {
200 { 'OK' }
201 { 'Created' }
204 { 'No Content' }
301 { 'Moved Permanently' }
302 { 'Found' }
304 { 'Not Modified' }
400 { 'Bad Request' }
401 { 'Unauthorized' }
403 { 'Forbidden' }
404 { 'Not Found' }
405 { 'Method Not Allowed' }
500 { 'Internal Server Error' }
502 { 'Bad Gateway' }
503 { 'Service Unavailable' }
else { 'Unknown' }
}
}
+28
View File
@@ -256,6 +256,34 @@ pub fn (mut c Context) status(code int) {
c.status_code = code
}
// redirect method - redirect to a URL with optional status code
pub fn (mut c Context) redirect(url string, status_code ...int) http.Response {
// Set default status code to 302 (Found) if not provided
mut code := 302
if status_code.len > 0 {
code = status_code[0]
}
// Set the status code
c.status(code)
// Set the Location header
c.headers['Location'] = url
// Build and return the response
mut headers := http.new_header()
headers.add_custom('Connection', 'keep-alive') or { }
for key, value in c.headers {
headers.add_custom(key, value) or { continue }
}
return http.Response{
status_code: c.status_code
header: headers
body: ''
}
}
// 处理器接口,使用 Context
+26 -18
View File
@@ -208,10 +208,34 @@ pub fn (router ContextHybridRouter) match_static_route(method string, path strin
return none
}
// Context 版本的动态路径匹配
// Context 版本的动态路径匹配(保留旧版本兼容)
fn (mut router ContextHybridRouter) match_dynamic_route(method string, path string) ?ContextRouteMatch {
// 先检查缓存
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) {
return cached
}
@@ -240,22 +264,6 @@ fn (mut router ContextHybridRouter) match_dynamic_route(method string, path stri
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 版本的获取所有路由
pub fn (router ContextHybridRouter) get_all_routes() ([]string, []string) {
mut static_paths := []string{}
+251
View File
@@ -0,0 +1,251 @@
// 高并发基准测试 - 用于对比 v-hono 内外性能
// 参数与外层 benchmark.go 保持一致: 500 并发, 100万请求
//
// 使用方法:
// 1. 启动服务器: v -enable-globals run v-hono/tests/test_picoev_server.v
// 2. 运行测试: go run v-hono/tests/benchmark_compare.go
package main
import (
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
baseURL = "http://127.0.0.1:9999"
connections = 500
requests = 1000000
timeout = 10 * time.Second
)
type Metrics struct {
TotalRequests int64
SuccessRequests int64
FailedRequests int64
TotalBytes int64
MinLatency time.Duration
MaxLatency time.Duration
TotalLatencyNs int64
StartTime time.Time
EndTime time.Time
}
func main() {
fmt.Println("🔥 V-Hono 高并发基准测试")
fmt.Println(strings.Repeat("=", 50))
fmt.Printf("服务器: %s\n", baseURL)
fmt.Printf("并发数: %d\n", connections)
fmt.Printf("请求数: %d\n", requests)
fmt.Printf("超时: %v\n", timeout)
fmt.Println()
// 检查服务器
if !checkServer() {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: v -enable-globals run v-hono/tests/test_picoev_server.v")
return
}
fmt.Println("✅ 服务器已就绪")
// 预热
fmt.Println("\n🔥 预热服务器...")
warmup()
fmt.Println("✅ 预热完成")
// 运行测试
testCases := []struct {
name string
path string
}{
{"健康检查", "/health"},
{"根路径", "/"},
{"JSON接口", "/json"},
{"动态路由", "/users/123"},
}
allResults := make(map[string]*Metrics)
for _, tc := range testCases {
fmt.Printf("\n🚀 测试: %s (%s)\n", tc.name, tc.path)
fmt.Println(strings.Repeat("-", 50))
metrics := runBenchmark(tc.path)
allResults[tc.name] = metrics
printMetrics(tc.name, metrics)
time.Sleep(2 * time.Second)
}
// 汇总
printSummary(allResults)
}
func checkServer() bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 3; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
resp.Body.Close()
return true
}
time.Sleep(500 * time.Millisecond)
}
return false
}
func warmup() {
client := &http.Client{Timeout: 5 * time.Second}
for i := 0; i < 100; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}
}
func runBenchmark(endpoint string) *Metrics {
url := baseURL + endpoint
metrics := &Metrics{
StartTime: time.Now(),
MinLatency: time.Hour,
}
client := &http.Client{
Timeout: timeout,
Transport: &http.Transport{
MaxIdleConns: connections,
MaxIdleConnsPerHost: connections,
IdleConnTimeout: 30 * time.Second,
},
}
requestsPerWorker := requests / connections
var wg sync.WaitGroup
var latencyMutex sync.Mutex
// 进度显示
done := make(chan bool)
go showProgress(metrics, done)
// 启动工作协程
for i := 0; i < connections; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < requestsPerWorker; j++ {
start := time.Now()
resp, err := client.Get(url)
latency := time.Since(start)
atomic.AddInt64(&metrics.TotalRequests, 1)
atomic.AddInt64(&metrics.TotalLatencyNs, int64(latency))
latencyMutex.Lock()
if latency < metrics.MinLatency {
metrics.MinLatency = latency
}
if latency > metrics.MaxLatency {
metrics.MaxLatency = latency
}
latencyMutex.Unlock()
if err != nil {
atomic.AddInt64(&metrics.FailedRequests, 1)
continue
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil || resp.StatusCode >= 400 {
atomic.AddInt64(&metrics.FailedRequests, 1)
} else {
atomic.AddInt64(&metrics.SuccessRequests, 1)
atomic.AddInt64(&metrics.TotalBytes, int64(len(body)))
}
}
}()
}
wg.Wait()
metrics.EndTime = time.Now()
done <- true
return metrics
}
func showProgress(metrics *Metrics, done chan bool) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-done:
fmt.Println()
return
case <-ticker.C:
current := atomic.LoadInt64(&metrics.TotalRequests)
elapsed := time.Since(metrics.StartTime).Seconds()
rps := float64(current) / elapsed
progress := float64(current) / float64(requests) * 100
fmt.Printf("\r进度: %.1f%% | 完成: %d | RPS: %.0f | 耗时: %.1fs",
progress, current, rps, elapsed)
}
}
}
func printMetrics(name string, m *Metrics) {
duration := m.EndTime.Sub(m.StartTime)
avgLatency := time.Duration(m.TotalLatencyNs / m.TotalRequests)
fmt.Printf("\n📊 %s - 测试结果\n", name)
fmt.Println(strings.Repeat("=", 40))
fmt.Printf("总请求数: %d\n", m.TotalRequests)
fmt.Printf("成功请求: %d\n", m.SuccessRequests)
fmt.Printf("失败请求: %d\n", m.FailedRequests)
fmt.Printf("成功率: %.2f%%\n", float64(m.SuccessRequests)/float64(m.TotalRequests)*100)
fmt.Printf("总耗时: %.2f 秒\n", duration.Seconds())
fmt.Printf("RPS: %.0f 请求/秒\n", float64(m.TotalRequests)/duration.Seconds())
fmt.Printf("最小延迟: %v\n", m.MinLatency)
fmt.Printf("最大延迟: %v\n", m.MaxLatency)
fmt.Printf("平均延迟: %v\n", avgLatency)
if m.TotalBytes > 0 {
throughputMB := float64(m.TotalBytes) / 1024 / 1024 / duration.Seconds()
fmt.Printf("数据传输: %.2f MB\n", float64(m.TotalBytes)/1024/1024)
fmt.Printf("吞吐量: %.2f MB/s\n", throughputMB)
}
}
func printSummary(results map[string]*Metrics) {
fmt.Printf("\n🏆 性能汇总报告\n")
fmt.Println(strings.Repeat("=", 60))
fmt.Printf("%-15s %-12s %-10s %-12s %-10s\n", "接口", "RPS", "成功率", "平均延迟", "吞吐量")
fmt.Println(strings.Repeat("-", 60))
for name, metrics := range results {
duration := metrics.EndTime.Sub(metrics.StartTime)
rps := float64(metrics.TotalRequests) / duration.Seconds()
successRate := float64(metrics.SuccessRequests) / float64(metrics.TotalRequests) * 100
avgLatency := time.Duration(metrics.TotalLatencyNs / metrics.TotalRequests)
throughput := float64(metrics.TotalBytes) / 1024 / 1024 / duration.Seconds()
fmt.Printf("%-15s %-12.0f %-9.1f%% %-12v %-8.1fMB/s\n",
name, rps, successRate, avgLatency, throughput)
}
fmt.Println("\n✅ 测试完成!")
}
+1 -1
View File
@@ -3,7 +3,7 @@
module main
import time
import hono
import meiseayoung.hono
import net.http
const iterations = 100_000
+1 -1
View File
@@ -4,7 +4,7 @@
module main
import time
import hono
import meiseayoung.hono
import net.http
// ============================================
+102
View File
@@ -0,0 +1,102 @@
package main
import (
"flag"
"fmt"
"io"
"math/rand"
"net/http"
"sort"
"sync"
"sync/atomic"
"time"
)
func main() {
url := flag.String("url", "http://127.0.0.1:3000", "Target base URL")
connections := flag.Int("c", 500, "Number of connections")
requests := flag.Int("n", 1000000, "Total number of requests")
flag.Parse()
fmt.Printf("Benchmarking %s/users/:id\n", *url)
fmt.Printf("Connections: %d, Requests: %d\n\n", *connections, *requests)
client := &http.Client{
Transport: &http.Transport{
MaxIdleConns: *connections,
MaxIdleConnsPerHost: *connections,
MaxConnsPerHost: *connections,
IdleConnTimeout: 90 * time.Second,
},
Timeout: 10 * time.Second,
}
var completed int64
var errors int64
var latencies []int64
var mu sync.Mutex
totalReqs := int64(*requests)
start := time.Now()
var wg sync.WaitGroup
for i := 0; i < *connections; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
if atomic.LoadInt64(&completed)+atomic.LoadInt64(&errors) >= totalReqs {
return
}
reqStart := time.Now()
userId := rand.Intn(10000)
targetUrl := fmt.Sprintf("%s/users/%d", *url, userId)
resp, err := client.Get(targetUrl)
if err != nil {
atomic.AddInt64(&errors, 1)
continue
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
latency := time.Since(reqStart).Microseconds()
mu.Lock()
latencies = append(latencies, latency)
mu.Unlock()
atomic.AddInt64(&completed, 1)
}
}()
}
wg.Wait()
elapsed := time.Since(start).Seconds()
total := atomic.LoadInt64(&completed)
errs := atomic.LoadInt64(&errors)
rps := float64(total) / elapsed
mu.Lock()
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
var avg, p50, p95, p99 int64
if len(latencies) > 0 {
var sum int64
for _, l := range latencies {
sum += l
}
avg = sum / int64(len(latencies))
p50 = latencies[len(latencies)*50/100]
p95 = latencies[len(latencies)*95/100]
p99 = latencies[len(latencies)*99/100]
}
mu.Unlock()
fmt.Println("Results:")
fmt.Printf(" Requests: %d\n", total)
fmt.Printf(" Errors: %d\n", errs)
fmt.Printf(" Duration: %.2fs\n", elapsed)
fmt.Printf(" RPS: %.0f\n", rps)
fmt.Printf(" Latency avg: %.2fms\n", float64(avg)/1000)
fmt.Printf(" Latency p50: %.2fms\n", float64(p50)/1000)
fmt.Printf(" Latency p95: %.2fms\n", float64(p95)/1000)
fmt.Printf(" Latency p99: %.2fms\n", float64(p99)/1000)
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import time
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import os
import time
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
fn main() {
println('=== 测试缓存内存泄漏修复 ===')
+81
View File
@@ -0,0 +1,81 @@
// 测试缓存命中率
module main
import meiseayoung.hono
import net.http
import time
fn main() {
println('=== 缓存命中率测试 ===')
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
user_id := c.params['id'] or { 'unknown' }
return c.json('{"user_id": "${user_id}"}')
})
// 获取 FastRouter 引用
mut router := app.fast_router
// 预热:先匹配一次让缓存生效
println('\n1. 预热阶段')
_ := router.match_route('GET', '/users/123')
// 获取初始统计
cache_size, cache_capacity := router.get_cache_stats()
println(' 缓存大小: ${cache_size}/${cache_capacity}')
// 测试相同路径的匹配
println('\n2. 测试相同路径 /users/123 匹配 1000 次')
sw := time.new_stopwatch()
for _ in 0 .. 1000 {
_ := router.match_route('GET', '/users/123')
}
elapsed := sw.elapsed()
println(' 耗时: ${elapsed.microseconds()}μs')
println(' 平均: ${elapsed.microseconds() / 1000}μs/次')
// 获取缓存统计
cache_size2, _ := router.get_cache_stats()
println(' 缓存大小: ${cache_size2}')
// 测试不同路径
println('\n3. 测试不同路径 /users/1 到 /users/1000')
sw2 := time.new_stopwatch()
for i in 1 .. 1001 {
_ := router.match_route('GET', '/users/${i}')
}
elapsed2 := sw2.elapsed()
println(' 耗时: ${elapsed2.microseconds()}μs')
println(' 平均: ${elapsed2.microseconds() / 1000}μs/次')
// 获取最终缓存统计
cache_size3, _ := router.get_cache_stats()
println(' 缓存大小: ${cache_size3}')
// 再次测试相同路径(应该命中缓存)
println('\n4. 再次测试 /users/500(应该命中缓存)')
sw3 := time.new_stopwatch()
for _ in 0 .. 1000 {
_ := router.match_route('GET', '/users/500')
}
elapsed3 := sw3.elapsed()
println(' 耗时: ${elapsed3.microseconds()}μs')
println(' 平均: ${elapsed3.microseconds() / 1000}μs/次')
// 详细统计
println('\n5. 详细统计')
stats := router.get_detailed_stats()
for key, value in stats {
println(' ${key}: ${value}')
}
println('\n=== 测试完成 ===')
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import strings
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
fn test_default_config() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
fn main() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
import time
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import net.http
fn main() {
+381
View File
@@ -0,0 +1,381 @@
// FastCache 优化测试
// 验证高性能缓存的正确性和性能
module main
import meiseayoung.hono
import net.http
import time
struct TestResult {
mut:
name string
passed bool
detail string
}
fn main() {
println('╔═══════════════════════════════════════════════════════════════╗')
println('║ FastCache 优化测试 ║')
println('╚═══════════════════════════════════════════════════════════════╝')
println('')
mut results := []TestResult{}
// 1. 基本功能测试
results << test_basic_cache_operations()
// 2. 路由匹配正确性测试
results << test_route_matching_correctness()
// 3. 参数提取正确性测试
results << test_param_extraction()
// 4. 缓存命中测试
results << test_cache_hit()
// 5. 缓存容量测试
results << test_cache_capacity()
// 6. 多路由并发测试
results << test_multiple_routes()
// 7. 性能基准测试
results << test_performance_benchmark()
// 8. 缓存一致性测试
results << test_cache_consistency()
// 打印结果
println('')
println('═══════════════════════════════════════════════════════════════')
println('📊 测试结果汇总')
println('═══════════════════════════════════════════════════════════════')
mut passed := 0
mut failed := 0
for result in results {
status := if result.passed { '✅' } else { '❌' }
println('${status} ${result.name}')
if result.detail.len > 0 {
println(' ${result.detail}')
}
if result.passed {
passed++
} else {
failed++
}
}
println('')
println('总计: ${passed}/${results.len} 通过')
if failed == 0 {
println('🎉 所有测试通过!FastCache 优化验证成功!')
} else {
println('⚠️ 有 ${failed} 个测试失败')
}
}
// 1. 基本缓存操作测试
fn test_basic_cache_operations() TestResult {
mut cache := hono.FastRouteCache.new(100)
// 测试 put 和 get
test_match := hono.ContextRouteMatch{
params: {'id': '123'}
path: '/users/:id'
}
cache.put('GET:/users/123', test_match)
if result := cache.get('GET:/users/123') {
if result.params['id'] or { '' } == '123' {
size, capacity := cache.get_stats()
return TestResult{
name: '基本缓存操作'
passed: true
detail: '缓存大小: ${size}/${capacity}'
}
}
}
return TestResult{
name: '基本缓存操作'
passed: false
detail: '缓存 get/put 失败'
}
}
// 2. 路由匹配正确性测试
fn test_route_matching_correctness() TestResult {
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
return c.text('user')
})
app.get('/posts/:post_id/comments/:comment_id', fn (mut c hono.Context) http.Response {
return c.text('comment')
})
mut router := app.fast_router
// 测试单参数路由
if match1 := router.match_route('GET', '/users/456') {
if match1.params['id'] or { '' } != '456' {
return TestResult{name: '路由匹配正确性', passed: false, detail: '单参数提取错误'}
}
} else {
return TestResult{name: '路由匹配正确性', passed: false, detail: '单参数路由匹配失败'}
}
// 测试多参数路由
if match2 := router.match_route('GET', '/posts/100/comments/200') {
post_id := match2.params['post_id'] or { '' }
comment_id := match2.params['comment_id'] or { '' }
if post_id != '100' || comment_id != '200' {
return TestResult{name: '路由匹配正确性', passed: false, detail: '多参数提取错误: post_id=${post_id}, comment_id=${comment_id}'}
}
} else {
return TestResult{name: '路由匹配正确性', passed: false, detail: '多参数路由匹配失败'}
}
return TestResult{name: '路由匹配正确性', passed: true, detail: '单参数和多参数路由均正确'}
}
// 3. 参数提取正确性测试
fn test_param_extraction() TestResult {
mut app := hono.Hono.new()
app.get('/api/:version/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
return c.text('ok')
})
mut router := app.fast_router
test_cases := [
['/api/v1/users/100/posts/200', 'v1', '100', '200'],
['/api/v2/users/abc/posts/xyz', 'v2', 'abc', 'xyz'],
['/api/beta/users/user-123/posts/post-456', 'beta', 'user-123', 'post-456'],
]
for tc in test_cases {
path := tc[0]
expected_version := tc[1]
expected_user := tc[2]
expected_post := tc[3]
if match_result := router.match_route('GET', path) {
version := match_result.params['version'] or { '' }
user_id := match_result.params['user_id'] or { '' }
post_id := match_result.params['post_id'] or { '' }
if version != expected_version || user_id != expected_user || post_id != expected_post {
return TestResult{
name: '参数提取正确性'
passed: false
detail: '路径 ${path} 参数提取错误'
}
}
} else {
return TestResult{name: '参数提取正确性', passed: false, detail: '路径 ${path} 匹配失败'}
}
}
return TestResult{name: '参数提取正确性', passed: true, detail: '${test_cases.len} 个测试用例全部通过'}
}
// 4. 缓存命中测试
fn test_cache_hit() TestResult {
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
return c.text('user')
})
mut router := app.fast_router
// 第一次匹配(缓存未命中,需要正则匹配)
_ := router.match_route('GET', '/users/123')
// 获取缓存统计
cache_size1, _ := router.fast_cache.get_stats()
// 第二次匹配(应该命中缓存)
if match2 := router.match_route('GET', '/users/123') {
if match2.params['id'] or { '' } == '123' {
cache_size2, _ := router.fast_cache.get_stats()
return TestResult{
name: '缓存命中测试'
passed: true
detail: '缓存大小: ${cache_size1} -> ${cache_size2},参数正确'
}
}
}
return TestResult{name: '缓存命中测试', passed: false, detail: '缓存命中后参数错误'}
}
// 5. 缓存容量测试
fn test_cache_capacity() TestResult {
mut cache := hono.FastRouteCache.new(10) // 小容量测试
// 填满缓存
for i in 0 .. 10 {
cache.put('key${i}', hono.ContextRouteMatch{path: '/test/${i}'})
}
size1, _ := cache.get_stats()
if size1 != 10 {
return TestResult{name: '缓存容量测试', passed: false, detail: '填充后大小错误: ${size1}'}
}
// 超出容量,应该清空重建
cache.put('key_overflow', hono.ContextRouteMatch{path: '/overflow'})
size2, _ := cache.get_stats()
if size2 != 1 {
return TestResult{name: '缓存容量测试', passed: false, detail: '溢出后大小错误: ${size2}'}
}
// 验证新数据存在
if _ := cache.get('key_overflow') {
return TestResult{name: '缓存容量测试', passed: true, detail: '容量限制和清空重建正常'}
}
return TestResult{name: '缓存容量测试', passed: false, detail: '溢出后数据丢失'}
}
// 6. 多路由并发测试
fn test_multiple_routes() TestResult {
mut app := hono.Hono.new()
// 注册多个路由
app.get('/users/:id', fn (mut c hono.Context) http.Response { return c.text('user') })
app.get('/posts/:id', fn (mut c hono.Context) http.Response { return c.text('post') })
app.get('/comments/:id', fn (mut c hono.Context) http.Response { return c.text('comment') })
app.get('/tags/:name', fn (mut c hono.Context) http.Response { return c.text('tag') })
mut router := app.fast_router
// 交替匹配不同路由
test_paths := [
['/users/1', 'id', '1'],
['/posts/2', 'id', '2'],
['/comments/3', 'id', '3'],
['/tags/golang', 'name', 'golang'],
['/users/100', 'id', '100'],
['/posts/200', 'id', '200'],
]
for tc in test_paths {
path := tc[0]
param_name := tc[1]
expected_value := tc[2]
if match_result := router.match_route('GET', path) {
actual_value := match_result.params[param_name] or { '' }
if actual_value != expected_value {
return TestResult{
name: '多路由并发测试'
passed: false
detail: '路径 ${path} 参数错误: 期望 ${expected_value}, 实际 ${actual_value}'
}
}
} else {
return TestResult{name: '多路由并发测试', passed: false, detail: '路径 ${path} 匹配失败'}
}
}
return TestResult{name: '多路由并发测试', passed: true, detail: '${test_paths.len} 个路径全部正确'}
}
// 7. 性能基准测试
fn test_performance_benchmark() TestResult {
mut app := hono.Hono.new()
app.get('/users/:id', fn (mut c hono.Context) http.Response {
return c.text('user')
})
mut router := app.fast_router
// 预热
for i in 0 .. 100 {
_ := router.match_route('GET', '/users/${i}')
}
// 测试缓存命中性能
iterations := 10000
sw := time.new_stopwatch()
for _ in 0 .. iterations {
_ := router.match_route('GET', '/users/50') // 命中缓存
}
elapsed := sw.elapsed()
avg_ns := elapsed.nanoseconds() / iterations
avg_us := f64(avg_ns) / 1000.0
// 缓存命中应该 < 1μs
if avg_us < 1.0 {
return TestResult{
name: '性能基准测试'
passed: true
detail: '缓存命中平均耗时: ${avg_us:.3f}μs (< 1μs ✓)'
}
} else if avg_us < 5.0 {
return TestResult{
name: '性能基准测试'
passed: true
detail: '缓存命中平均耗时: ${avg_us:.3f}μs (< 5μs, 可接受)'
}
}
return TestResult{
name: '性能基准测试'
passed: false
detail: '缓存命中平均耗时: ${avg_us:.3f}μs (> 5μs, 过慢)'
}
}
// 8. 缓存一致性测试
fn test_cache_consistency() TestResult {
mut app := hono.Hono.new()
app.get('/items/:id', fn (mut c hono.Context) http.Response {
return c.text('item')
})
mut router := app.fast_router
// 多次匹配相同路径,验证结果一致
mut results := []string{}
for _ in 0 .. 100 {
if match_result := router.match_route('GET', '/items/999') {
results << match_result.params['id'] or { 'error' }
} else {
results << 'no_match'
}
}
// 检查所有结果是否一致
first := results[0]
for i, r in results {
if r != first {
return TestResult{
name: '缓存一致性测试'
passed: false
detail: '第 ${i} 次结果不一致: ${r} != ${first}'
}
}
}
if first == '999' {
return TestResult{name: '缓存一致性测试', passed: true, detail: '100 次匹配结果完全一致'}
}
return TestResult{name: '缓存一致性测试', passed: false, detail: '参数值错误: ${first}'}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+245
View File
@@ -0,0 +1,245 @@
// 高并发测试 (5000-10000 并发)
//
// 使用方法:
// 1. 启动服务器 (必须设置 ulimit): ulimit -n 65535 && ./bench_server_usockets
// 2. 运行测试: ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go
// 3. 单独测试某个级别: ulimit -n 65535 && go run v-hono/tests/test_high_concurrency.go 8000
//
// 重要提示:
// - 服务器和客户端都需要设置 ulimit -n 65535
// - 连续测试多个并发级别时,建议每次测试前重启服务器
// - TIME_WAIT 连接会影响后续测试,建议等待 10 秒后再测试下一个级别
//
// 系统配置要求 (macOS):
// sudo sysctl -w kern.ipc.somaxconn=8192
// ulimit -n 65535
package main
import (
"fmt"
"io"
"net/http"
"os"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
)
type BenchResult struct {
Concurrency int
TotalReqs int64
SuccessReqs int64
RPS float64
AvgLatency float64
P99Latency float64
SuccessRate float64
}
func main() {
baseURL := "http://127.0.0.1:8080/"
duration := 10 * time.Second
// 默认测试级别: 5000, 6000, 7000, 8000, 9000, 10000
concurrencyLevels := []int{5000, 6000, 7000, 8000, 9000, 10000}
// 支持命令行参数指定单个并发级别
if len(os.Args) > 1 {
level, err := strconv.Atoi(os.Args[1])
if err == nil {
concurrencyLevels = []int{level}
}
}
fmt.Println("╔═══════════════════════════════════════════════════════════════════════════╗")
fmt.Println("║ v-hono 高并发测试 (5000-10000 并发) ║")
fmt.Println("╚═══════════════════════════════════════════════════════════════════════════╝")
fmt.Println()
// 检查服务器是否运行
if !checkServer(baseURL) {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: ./bench_server_usockets")
fmt.Println()
fmt.Println(" 系统配置要求:")
fmt.Println(" - macOS: sudo sysctl -w kern.ipc.somaxconn=8192")
fmt.Println(" - ulimit -n 65535")
return
}
fmt.Println("✅ 服务器已就绪")
fmt.Println()
results := make([]BenchResult, 0, len(concurrencyLevels))
for _, conns := range concurrencyLevels {
result := runBenchmark(baseURL, conns, duration)
results = append(results, result)
// 测试间隔,让系统恢复 (TIME_WAIT 连接需要时间释放)
// macOS TIME_WAIT 默认 15-30 秒,建议等待 60 秒
if len(concurrencyLevels) > 1 {
fmt.Println(" ⏳ 等待 60 秒让系统恢复 (TIME_WAIT 连接释放)...")
time.Sleep(60 * time.Second)
}
}
// 输出汇总报告
printSummary(results)
}
func checkServer(baseURL string) bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL)
if err == nil && resp.StatusCode < 400 {
resp.Body.Close()
return true
}
time.Sleep(200 * time.Millisecond)
}
return false
}
func runBenchmark(baseURL string, conns int, duration time.Duration) BenchResult {
fmt.Printf("🔥 测试 %d 并发连接 (持续 %v)\n", conns, duration)
var total, success int64
var totalLatencyNs int64
latencies := make([]int64, 0, 1000000)
var mu sync.Mutex
client := &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
MaxIdleConns: conns * 2,
MaxIdleConnsPerHost: conns * 2,
MaxConnsPerHost: 0,
IdleConnTimeout: 120 * time.Second,
DisableKeepAlives: false,
ForceAttemptHTTP2: false,
},
}
var wg sync.WaitGroup
stop := make(chan struct{})
start := time.Now()
// 同时启动所有连接
for i := 0; i < conns; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-stop:
return
default:
t0 := time.Now()
resp, err := client.Get(baseURL)
lat := time.Since(t0).Nanoseconds()
atomic.AddInt64(&total, 1)
atomic.AddInt64(&totalLatencyNs, lat)
mu.Lock()
latencies = append(latencies, lat)
mu.Unlock()
if err != nil {
continue
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
if resp.StatusCode < 400 {
atomic.AddInt64(&success, 1)
}
}
}
}()
}
time.Sleep(duration)
close(stop)
wg.Wait()
elapsed := time.Since(start)
// 计算 P99
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
p99 := int64(0)
if len(latencies) > 0 {
idx := len(latencies) * 99 / 100
p99 = latencies[idx]
}
avgLat := float64(totalLatencyNs) / float64(total) / 1e6
rps := float64(total) / elapsed.Seconds()
successRate := float64(success) / float64(total) * 100
// 判断测试结果
status := "✅"
if successRate < 99.0 {
status = "⚠️"
}
if successRate < 90.0 {
status = "❌"
}
fmt.Printf(" %s RPS: %8.0f Avg: %6.2fms P99: %6.2fms Success: %.1f%%\n",
status, rps, avgLat, float64(p99)/1e6, successRate)
fmt.Println()
return BenchResult{
Concurrency: conns,
TotalReqs: total,
SuccessReqs: success,
RPS: rps,
AvgLatency: avgLat,
P99Latency: float64(p99) / 1e6,
SuccessRate: successRate,
}
}
func printSummary(results []BenchResult) {
if len(results) <= 1 {
return
}
fmt.Println("═══════════════════════════════════════════════════════════════════════════")
fmt.Println(" 📊 测试结果汇总")
fmt.Println("═══════════════════════════════════════════════════════════════════════════")
fmt.Println()
fmt.Println("┌──────────────┬──────────────┬──────────────┬──────────────┬──────────────┐")
fmt.Println("│ 并发数 │ RPS │ 平均延迟 │ P99延迟 │ 成功率 │")
fmt.Println("├──────────────┼──────────────┼──────────────┼──────────────┼──────────────┤")
allPassed := true
for _, r := range results {
status := "✅"
if r.SuccessRate < 99.0 {
status = "⚠️"
allPassed = false
}
if r.SuccessRate < 90.0 {
status = "❌"
allPassed = false
}
fmt.Printf("│ %s %6d │ %10.0f │ %8.2fms │ %8.2fms │ %8.1f%% │\n",
status, r.Concurrency, r.RPS, r.AvgLatency, r.P99Latency, r.SuccessRate)
}
fmt.Println("└──────────────┴──────────────┴──────────────┴──────────────┴──────────────┘")
fmt.Println()
if allPassed {
fmt.Println("🎉 所有高并发测试通过!v-hono uSockets 后端表现优秀!")
} else {
fmt.Println("⚠️ 部分测试未达到 99% 成功率,请检查系统配置")
fmt.Println(" - macOS: sudo sysctl -w kern.ipc.somaxconn=8192")
fmt.Println(" - ulimit -n 65535")
}
fmt.Println()
}
+282
View File
@@ -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('测试完成!')
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
import os
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
fn main() {
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
import time
+355
View File
@@ -0,0 +1,355 @@
// 中间件优化测试
// 测试三个优化点:
// 1. 零中间件快速路径
// 2. 中间件预计算(启动时排序)
// 3. 复用 cache key
import meiseayoung.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()
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+68
View File
@@ -0,0 +1,68 @@
// Keep-Alive HTTP 基准测试
module main
import net
import time
fn main() {
addr := '127.0.0.1:9999'
requests := 10000
println('=== Keep-Alive HTTP 基准测试 ===')
println('目标: ${addr}')
println('请求数: ${requests}')
println('')
// 建立连接
mut conn := net.dial_tcp(addr) or {
println('连接失败: ${err}')
return
}
defer { conn.close() or {} }
// 预热
println('预热中...')
for _ in 0 .. 100 {
send_keepalive_request(mut conn, addr) or {
// 重连
conn = net.dial_tcp(addr) or { continue }
continue
}
}
// 正式测试
println('开始测试...')
sw := time.new_stopwatch()
mut success := 0
for _ in 0 .. requests {
send_keepalive_request(mut conn, addr) or {
// 重连
conn = net.dial_tcp(addr) or { continue }
continue
}
success++
}
elapsed := sw.elapsed()
elapsed_ms := f64(elapsed.milliseconds())
rps := f64(success) * 1000.0 / elapsed_ms
avg_us := elapsed_ms * 1000.0 / f64(success)
println('')
println('=== 结果 ===')
println('成功请求: ${success}/${requests}')
println('总耗时: ${elapsed_ms:.0f}ms')
println('吞吐量: ${rps:.0f} req/s')
println('平均延迟: ${avg_us:.2f}μs')
}
fn send_keepalive_request(mut conn net.TcpConn, addr string) ! {
// 发送 HTTP 请求 (Keep-Alive)
request := 'GET /api/health HTTP/1.1\r\nHost: ${addr}\r\nConnection: keep-alive\r\n\r\n'
conn.write_string(request)!
// 读取响应头和体
mut buf := []u8{len: 256}
conn.read(mut buf) or {}
}
BIN
View File
Binary file not shown.
+360
View File
@@ -0,0 +1,360 @@
// picoev 优化集成测试 (Go 版本)
// 测试 picoev 服务器的完整功能,确保优化没有引入新问题
//
// 使用方法:
// 1. 先启动测试服务器: v -enable-globals run v-hono/tests/test_picoev_server.v
// 2. 运行测试: go run v-hono/tests/test_picoev_integration.go
package main
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
const baseURL = "http://127.0.0.1:9999"
type TestStats struct {
total int
passed int
failed int
errors []string
}
func (s *TestStats) run(name string, testFn func() bool) {
s.total++
fmt.Printf(" 🧪 %s... ", name)
if testFn() {
s.passed++
fmt.Println("✅")
} else {
s.failed++
s.errors = append(s.errors, name)
fmt.Println("❌")
}
}
func (s *TestStats) summary() {
fmt.Println()
fmt.Println("═══════════════════════════════════════════════════════════════")
fmt.Printf("📊 测试结果: %d/%d 通过\n", s.passed, s.total)
if s.failed > 0 {
fmt.Println("❌ 失败的测试:")
for _, err := range s.errors {
fmt.Printf(" - %s\n", err)
}
} else {
fmt.Println("🎉 所有测试通过!picoev 优化验证成功!")
}
fmt.Println("═══════════════════════════════════════════════════════════════")
}
func main() {
fmt.Println("╔═══════════════════════════════════════════════════════════════╗")
fmt.Println("║ picoev 优化集成测试 (Go) ║")
fmt.Println("╚═══════════════════════════════════════════════════════════════╝")
fmt.Println()
// 验证服务器是否运行
fmt.Println("🔍 检查测试服务器...")
if !checkServerReady() {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: v -enable-globals run v-hono/tests/test_picoev_server.v")
return
}
fmt.Println("✅ 服务器已就绪")
fmt.Println()
stats := &TestStats{}
// 1. 基本 GET 路由测试
fmt.Println("📦 1. 基本 GET 路由测试")
stats.run("GET 根路径", testGetRoot)
stats.run("GET 健康检查", testGetHealth)
stats.run("GET 静态路由", testGetStatic)
fmt.Println()
// 2. 动态路由测试
fmt.Println("📦 2. 动态路由测试")
stats.run("单参数路由", testSingleParam)
stats.run("多参数路由", testMultiParams)
stats.run("嵌套参数路由", testNestedParams)
fmt.Println()
// 3. 查询参数测试
fmt.Println("📦 3. 查询参数测试")
stats.run("单个查询参数", testSingleQuery)
stats.run("多个查询参数", testMultiQuery)
fmt.Println()
// 4. 响应格式测试
fmt.Println("📦 4. 响应格式测试")
stats.run("JSON 响应", testJSONResponse)
stats.run("HTML 响应", testHTMLResponse)
stats.run("自定义状态码 201", testCustomStatus)
fmt.Println()
// 5. 中间件测试
fmt.Println("📦 5. 中间件测试")
stats.run("全局中间件响应头", testMiddlewareHeader)
fmt.Println()
// 6. 404 处理测试
fmt.Println("📦 6. 错误处理测试")
stats.run("404 未找到", testNotFound)
fmt.Println()
// 7. Keep-Alive 测试
fmt.Println("📦 7. Keep-Alive 连接测试")
stats.run("连接复用", testKeepAlive)
fmt.Println()
// 8. 性能测试
fmt.Println("📦 8. 性能测试")
stats.run("响应时间 < 50ms", testResponseTime)
stats.run("吞吐量测试", testThroughput)
fmt.Println()
// 9. 高并发基准测试
fmt.Println("📦 9. Keep-Alive 基准测试")
testBenchmark()
fmt.Println()
// 输出总结
stats.summary()
}
// 检查服务器是否就绪
func checkServerReady() bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
resp.Body.Close()
return true
}
time.Sleep(200 * time.Millisecond)
}
return false
}
// ==================== 基本 GET 路由测试 ====================
func testGetRoot() bool {
resp, body := doGet("/")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "Hello")
}
func testGetHealth() bool {
resp, body := doGet("/health")
return resp != nil && resp.StatusCode == 200 && body == "OK"
}
func testGetStatic() bool {
resp, body := doGet("/api/health")
return resp != nil && resp.StatusCode == 200 && body == "OK"
}
// ==================== 动态路由测试 ====================
func testSingleParam() bool {
resp, body := doGet("/api/users/456")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "456")
}
func testMultiParams() bool {
resp, body := doGet("/api/users/123/posts/789")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "123") && strings.Contains(body, "789")
}
func testNestedParams() bool {
resp, body := doGet("/api/categories/tech/items/laptop")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "tech") && strings.Contains(body, "laptop")
}
// ==================== 查询参数测试 ====================
func testSingleQuery() bool {
resp, body := doGet("/api/search?q=test")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "test")
}
func testMultiQuery() bool {
resp, body := doGet("/api/search?q=hello&limit=10&page=1")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "hello")
}
// ==================== 响应格式测试 ====================
func testJSONResponse() bool {
resp, _ := doGet("/api/json")
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(contentType, "application/json")
}
func testHTMLResponse() bool {
resp, _ := doGet("/api/html")
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(contentType, "text/html")
}
func testCustomStatus() bool {
resp, _ := doGet("/api/created")
return resp != nil && resp.StatusCode == 201
}
// ==================== 中间件测试 ====================
func testMiddlewareHeader() bool {
resp, body := doGet("/api/health")
// 检查中间件添加的响应头
if resp == nil {
return false
}
middlewareHeader := resp.Header.Get("X-Middleware")
return resp.StatusCode == 200 && body == "OK" && middlewareHeader == "applied"
}
// ==================== 错误处理测试 ====================
func testNotFound() bool {
resp, _ := doGet("/nonexistent/path/here")
return resp != nil && resp.StatusCode == 404
}
// ==================== Keep-Alive 测试 ====================
func testKeepAlive() bool {
// 使用同一个 transport 发送多个请求
transport := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableKeepAlives: false,
}
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/api/health")
if err != nil || resp.StatusCode != 200 {
return false
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
return true
}
// ==================== 性能测试 ====================
func testResponseTime() bool {
client := &http.Client{Timeout: 5 * time.Second}
start := time.Now()
for i := 0; i < 10; i++ {
resp, err := client.Get(baseURL + "/api/health")
if err != nil {
return false
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
elapsed := time.Since(start)
avgMs := float64(elapsed.Milliseconds()) / 10.0
// 平均响应时间应小于 50ms
return avgMs < 50.0
}
func testThroughput() bool {
client := &http.Client{Timeout: 5 * time.Second}
requests := 50
success := 0
start := time.Now()
for i := 0; i < requests; i++ {
resp, err := client.Get(baseURL + "/api/health")
if err == nil && resp.StatusCode == 200 {
success++
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}
elapsed := time.Since(start)
rps := float64(success) * 1000.0 / float64(elapsed.Milliseconds())
fmt.Printf("(%.0f req/s) ", rps)
// 吞吐量应大于 20 req/s,成功率 > 90%
return rps > 20.0 && success >= requests*9/10
}
// Keep-Alive 基准测试
func testBenchmark() {
requests := 5000
conn, err := net.Dial("tcp", "127.0.0.1:9999")
if err != nil {
fmt.Println(" ❌ 连接失败:", err)
return
}
defer conn.Close()
// 预热
for i := 0; i < 100; i++ {
fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9999\r\nConnection: keep-alive\r\n\r\n")
buf := make([]byte, 256)
conn.Read(buf)
}
// 正式测试
start := time.Now()
success := 0
for i := 0; i < requests; i++ {
_, err := fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9999\r\nConnection: keep-alive\r\n\r\n")
if err != nil {
continue
}
buf := make([]byte, 256)
_, err = conn.Read(buf)
if err != nil {
continue
}
success++
}
elapsed := time.Since(start)
elapsedMs := float64(elapsed.Milliseconds())
rps := float64(success) * 1000.0 / elapsedMs
avgUs := elapsedMs * 1000.0 / float64(success)
fmt.Printf(" 成功请求: %d/%d\n", success, requests)
fmt.Printf(" 吞吐量: %.0f req/s\n", rps)
fmt.Printf(" 平均延迟: %.2fμs\n", avgUs)
}
// 辅助函数
func doGet(path string) (*http.Response, string) {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(baseURL + path)
if err != nil {
return nil, ""
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return resp, string(body)
}
BIN
View File
Binary file not shown.
+129
View File
@@ -0,0 +1,129 @@
// picoev 测试服务器
// 用于 test_picoev_integration.v 的测试
module main
import meiseayoung.hono
import net.http
fn main() {
mut app := hono.Hono.new()
// 全局中间件 - 添加自定义响应头
app.use(fn (mut c hono.Context, next fn (mut hono.Context) http.Response) http.Response {
mut resp := next(mut c)
c.headers['X-Middleware'] = 'applied'
return resp
})
// ==================== 基本路由 ====================
// 根路径
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello World')
})
// 健康检查
app.get('/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
app.get('/api/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
// ==================== CRUD 路由 ====================
app.get('/api/users', fn (mut c hono.Context) http.Response {
return c.json('{"users": []}')
})
app.post('/api/users', fn (mut c hono.Context) http.Response {
c.status(201)
return c.json('{"created": true}')
})
app.get('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}"}')
})
app.put('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}", "updated": true}')
})
app.delete('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}", "deleted": true}')
})
app.patch('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}", "patched": true}')
})
// ==================== 多参数路由 ====================
app.get('/api/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
user_id := c.params['user_id'] or { '' }
post_id := c.params['post_id'] or { '' }
return c.json('{"user_id": "${user_id}", "post_id": "${post_id}"}')
})
app.get('/api/categories/:category/items/:item', fn (mut c hono.Context) http.Response {
category := c.params['category'] or { '' }
item := c.params['item'] or { '' }
return c.json('{"category": "${category}", "item": "${item}"}')
})
// ==================== 查询参数路由 ====================
app.get('/api/search', fn (mut c hono.Context) http.Response {
q := c.query['q'] or { '' }
limit := c.query['limit'] or { '10' }
page := c.query['page'] or { '1' }
return c.json('{"query": "${q}", "limit": ${limit}, "page": ${page}}')
})
// ==================== 响应格式路由 ====================
app.get('/api/json', fn (mut c hono.Context) http.Response {
return c.json('{"message": "JSON response"}')
})
app.get('/api/html', fn (mut c hono.Context) http.Response {
return c.html('<html><body><h1>HTML Response</h1></body></html>')
})
app.get('/api/created', fn (mut c hono.Context) http.Response {
c.status(201)
return c.json('{"created": true}')
})
app.get('/api/custom-header', fn (mut c hono.Context) http.Response {
c.headers['X-Custom-Header'] = 'custom-value'
return c.text('OK')
})
// ==================== 中间件测试路由 ====================
app.get('/api/middleware-test', fn (mut c hono.Context) http.Response {
return c.text('middleware test')
})
app.get('/api/middleware-order', fn (mut c hono.Context) http.Response {
return c.json('{"order": "correct"}')
})
// ==================== 自定义 404 ====================
app.not_found(fn (mut c hono.Context) http.Response {
c.status(404)
return c.json('{"error": "Not Found", "path": "${c.path}"}')
})
// 启动服务器
println('[test-server] Starting on port 9999...')
app.listen(':9999')
}
+208
View File
@@ -0,0 +1,208 @@
import meiseayoung.hono
import net.http
// 重定向功能测试
fn redirect_basic_test() bool {
mut c := hono.Context.new(
http.Request{
method: .get
url: '/test'
},
map[string]string{},
map[string]string{},
''
)
response := c.redirect('https://example.com')
if response.status_code != 302 {
return false
}
location := response.header.get_custom('Location') or { '' }
if location != 'https://example.com' {
return false
}
if response.body != '' {
return false
}
return true
}
fn redirect_with_status_test() bool {
mut c := hono.Context.new(
http.Request{
method: .get
url: '/test'
},
map[string]string{},
map[string]string{},
''
)
response := c.redirect('https://example.com', 301)
if response.status_code != 301 {
return false
}
location := response.header.get_custom('Location') or { '' }
if location != 'https://example.com' {
return false
}
if response.body != '' {
return false
}
return true
}
fn redirect_multiple_status_codes_test() bool {
status_codes := [301, 302, 303, 307, 308]
for code in status_codes {
mut c := hono.Context.new(
http.Request{
method: .get
url: '/test'
},
map[string]string{},
map[string]string{},
''
)
response := c.redirect('https://example.com', code)
if response.status_code != code {
return false
}
location := response.header.get_custom('Location') or { '' }
if location != 'https://example.com' {
return false
}
if response.body != '' {
return false
}
}
return true
}
fn redirect_relative_url_test() bool {
mut c := hono.Context.new(
http.Request{
method: .get
url: '/test'
},
map[string]string{},
map[string]string{},
''
)
response := c.redirect('/relative-path')
if response.status_code != 302 {
return false
}
location := response.header.get_custom('Location') or { '' }
if location != '/relative-path' {
return false
}
return true
}
fn redirect_with_existing_headers_test() bool {
mut c := hono.Context.new(
http.Request{
method: .get
url: '/test'
},
map[string]string{},
map[string]string{},
''
)
// Set some existing headers
c.headers['X-Custom-Header'] = 'custom-value'
c.headers['Cache-Control'] = 'no-cache'
response := c.redirect('https://example.com')
if response.status_code != 302 {
return false
}
location := response.header.get_custom('Location') or { '' }
if location != 'https://example.com' {
return false
}
custom_header := response.header.get_custom('X-Custom-Header') or { '' }
if custom_header != 'custom-value' {
return false
}
cache_control := response.header.get_custom('Cache-Control') or { '' }
if cache_control != 'no-cache' {
return false
}
return true
}
// 测试统计结构
struct TestStats {
mut:
total_tests int
passed_tests int
failed_tests int
}
fn (mut stats TestStats) run_test(test_name string, test_func fn() bool) {
stats.total_tests++
print('🧪 ${test_name}... ')
if test_func() {
stats.passed_tests++
println('✅')
} else {
stats.failed_tests++
println('❌')
}
}
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} 个测试失败')
}
}
fn main() {
println('🚀 开始重定向功能测试...\n')
mut stats := TestStats{}
// 运行所有重定向测试
stats.run_test('基本重定向 (302)', redirect_basic_test)
stats.run_test('自定义状态码重定向 (301)', redirect_with_status_test)
stats.run_test('多种状态码测试', redirect_multiple_status_codes_test)
stats.run_test('相对路径重定向', redirect_relative_url_test)
stats.run_test('保持现有头部信息', redirect_with_existing_headers_test)
// 打印测试总结
stats.print_summary()
}
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
import regex
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
import regex
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
fn main() {
println('=== 测试输入验证和路径安全 ===')
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import time
import net.http
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
// 简化的测试统计
+1 -1
View File
@@ -1,4 +1,4 @@
import hono
import meiseayoung.hono
import os
import time
import strings
+268
View File
@@ -0,0 +1,268 @@
// uSockets 集成测试 (Go 版本)
//
// 使用方法:
// 1. 先启动测试服务器: v -enable-globals run v-hono/tests/test_usockets_server.v
// 2. 运行测试: go run v-hono/tests/test_usockets_integration.go
package main
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
const baseURL = "http://127.0.0.1:9998"
type TestStats struct {
total int
passed int
failed int
errors []string
}
func (s *TestStats) run(name string, testFn func() bool) {
s.total++
fmt.Printf(" 🧪 %s... ", name)
if testFn() {
s.passed++
fmt.Println("✅")
} else {
s.failed++
s.errors = append(s.errors, name)
fmt.Println("❌")
}
}
func (s *TestStats) summary() {
fmt.Println()
fmt.Println("═══════════════════════════════════════════════════════════════")
fmt.Printf("📊 测试结果: %d/%d 通过\n", s.passed, s.total)
if s.failed > 0 {
fmt.Println("❌ 失败的测试:")
for _, err := range s.errors {
fmt.Printf(" - %s\n", err)
}
} else {
fmt.Println("🎉 所有测试通过!uSockets 后端验证成功!")
}
fmt.Println("═══════════════════════════════════════════════════════════════")
}
func main() {
fmt.Println("╔═══════════════════════════════════════════════════════════════╗")
fmt.Println("║ uSockets 集成测试 (Go) ║")
fmt.Println("╚═══════════════════════════════════════════════════════════════╝")
fmt.Println()
// 验证服务器是否运行
fmt.Println("🔍 检查 uSockets 测试服务器...")
if !checkServerReady() {
fmt.Println("❌ 服务器未运行")
fmt.Println(" 请先启动: v -enable-globals run v-hono/tests/test_usockets_server.v")
return
}
fmt.Println("✅ 服务器已就绪")
fmt.Println()
stats := &TestStats{}
// 1. 基本路由测试
fmt.Println("📦 1. 基本路由测试")
stats.run("GET /", testGetRoot)
stats.run("GET /health", testGetHealth)
fmt.Println()
// 2. JSON 响应测试
fmt.Println("📦 2. JSON 响应测试")
stats.run("GET /api/json", testJSONResponse)
fmt.Println()
// 3. 动态路由测试
fmt.Println("📦 3. 动态路由测试")
stats.run("GET /api/users/:id", testSingleParam)
stats.run("GET /api/users/:user_id/posts/:post_id", testMultiParams)
fmt.Println()
// 4. 查询参数测试
fmt.Println("📦 4. 查询参数测试")
stats.run("GET /api/search?q=hello", testQueryParam)
fmt.Println()
// 5. 404 测试
fmt.Println("📦 5. 404 测试")
stats.run("404 Not Found", testNotFound)
fmt.Println()
// 6. Keep-Alive 测试
fmt.Println("📦 6. Keep-Alive 连接测试")
stats.run("Keep-Alive 连接复用", testKeepAlive)
fmt.Println()
// 7. 性能测试
fmt.Println("📦 7. 性能测试")
stats.run("吞吐量测试", testThroughput)
fmt.Println()
// 8. 高并发基准测试
fmt.Println("📦 8. Keep-Alive 基准测试")
testBenchmark()
fmt.Println()
// 输出总结
stats.summary()
}
func checkServerReady() bool {
client := &http.Client{Timeout: 2 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
resp.Body.Close()
return true
}
time.Sleep(200 * time.Millisecond)
}
return false
}
func testGetRoot() bool {
resp, body := doGet("/")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "Hello from uSockets")
}
func testGetHealth() bool {
resp, body := doGet("/health")
return resp != nil && resp.StatusCode == 200 && body == "OK"
}
func testJSONResponse() bool {
resp, body := doGet("/api/json")
if resp == nil {
return false
}
contentType := resp.Header.Get("Content-Type")
return resp.StatusCode == 200 && strings.Contains(contentType, "application/json") && strings.Contains(body, "Hello JSON")
}
func testSingleParam() bool {
resp, body := doGet("/api/users/123")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "123")
}
func testMultiParams() bool {
resp, body := doGet("/api/users/100/posts/200")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "100") && strings.Contains(body, "200")
}
func testQueryParam() bool {
resp, body := doGet("/api/search?q=hello")
return resp != nil && resp.StatusCode == 200 && strings.Contains(body, "hello")
}
func testNotFound() bool {
resp, _ := doGet("/nonexistent")
return resp != nil && resp.StatusCode == 404
}
func testKeepAlive() bool {
transport := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableKeepAlives: false,
}
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
for i := 0; i < 5; i++ {
resp, err := client.Get(baseURL + "/health")
if err != nil || resp.StatusCode != 200 {
return false
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
return true
}
func testThroughput() bool {
client := &http.Client{Timeout: 5 * time.Second}
requests := 100
success := 0
start := time.Now()
for i := 0; i < requests; i++ {
resp, err := client.Get(baseURL + "/health")
if err == nil && resp.StatusCode == 200 {
success++
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}
elapsed := time.Since(start)
rps := float64(success) * 1000.0 / float64(elapsed.Milliseconds())
fmt.Printf("(%.0f req/s) ", rps)
return success >= requests*9/10
}
func testBenchmark() {
requests := 5000
conn, err := net.Dial("tcp", "127.0.0.1:9998")
if err != nil {
fmt.Println(" ❌ 连接失败:", err)
return
}
defer conn.Close()
// 预热
for i := 0; i < 100; i++ {
fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9998\r\nConnection: keep-alive\r\n\r\n")
buf := make([]byte, 256)
conn.Read(buf)
}
// 正式测试
start := time.Now()
success := 0
for i := 0; i < requests; i++ {
_, err := fmt.Fprintf(conn, "GET /health HTTP/1.1\r\nHost: 127.0.0.1:9998\r\nConnection: keep-alive\r\n\r\n")
if err != nil {
continue
}
buf := make([]byte, 256)
_, err = conn.Read(buf)
if err != nil {
continue
}
success++
}
elapsed := time.Since(start)
elapsedMs := float64(elapsed.Milliseconds())
rps := float64(success) * 1000.0 / elapsedMs
avgUs := elapsedMs * 1000.0 / float64(success)
fmt.Printf(" 成功请求: %d/%d\n", success, requests)
fmt.Printf(" 吞吐量: %.0f req/s\n", rps)
fmt.Printf(" 平均延迟: %.2fμs\n", avgUs)
}
func doGet(path string) (*http.Response, string) {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(baseURL + path)
if err != nil {
return nil, ""
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return resp, string(body)
}
+50
View File
@@ -0,0 +1,50 @@
// uSockets 测试服务器
module main
import net.http
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
// 基本路由
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello from uSockets!')
})
app.get('/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
// JSON 响应
app.get('/api/json', fn (mut c hono.Context) http.Response {
return c.json('{"message": "Hello JSON"}')
})
// 动态路由
app.get('/api/users/:id', fn (mut c hono.Context) http.Response {
id := c.params['id'] or { '' }
return c.json('{"id": "${id}"}')
})
app.get('/api/users/:user_id/posts/:post_id', fn (mut c hono.Context) http.Response {
user_id := c.params['user_id'] or { '' }
post_id := c.params['post_id'] or { '' }
return c.json('{"user_id": "${user_id}", "post_id": "${post_id}"}')
})
// 查询参数
app.get('/api/search', fn (mut c hono.Context) http.Response {
q := c.query['q'] or { '' }
return c.json('{"query": "${q}"}')
})
// 404 处理
app.not_found(fn (mut c hono.Context) http.Response {
c.status(404)
return c.json('{"error": "Not Found"}')
})
println('[usockets-test-server] Starting on port 9998...')
app.listen_usockets(9998)
}
+44
View File
@@ -0,0 +1,44 @@
// uSockets 简化测试服务器 - 与外层 main.v 配置一致
module main
import meiseayoung.hono
import net.http
import x.json2
// JSON 响应结构体
struct JsonResponse {
message string
}
struct UserResponse {
user_id string
}
fn main() {
mut app := hono.Hono.new()
// 与外层 main.v 完全一致的路由配置(无中间件)
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello, World!')
})
app.get('/json', fn (mut c hono.Context) http.Response {
data := JsonResponse{message: 'Hello, JSON!'}
json_str := json2.encode(data)
return c.json(json_str)
})
app.get('/users/:id', fn (mut c hono.Context) http.Response {
user_id := c.params['id'] or { 'unknown' }
data := UserResponse{user_id: user_id}
json_str := json2.encode(data)
return c.json(json_str)
})
app.get('/health', fn (mut c hono.Context) http.Response {
return c.text('OK')
})
println('[usockets-simple] Starting on port 9999 (uSockets)...')
app.listen_usockets(9999)
}
+10 -2
View File
@@ -227,10 +227,18 @@ pub fn (mut manager ChunkUploadManager) handle_chunk_upload(mut ctx Context) htt
return ctx.json('{"success": true, "chunk_index": $chunk_index, "all_chunk_uploaded": false, "message": "Chunk uploaded successfully"}')
}
// 合并请求结构
pub struct MergeRequest {
pub:
file_hash string @[json: 'file_hash']
filename string
total_chunks int @[json: 'total_chunks']
}
// 处理分片合并
pub fn (mut manager ChunkUploadManager) handle_chunk_merge(mut ctx Context) http.Response {
// 解析请求体
merge_request := hono.parse_merge_request(ctx.body) or {
// 使用 x.json2 解析请求体
merge_request := json2.decode[MergeRequest](ctx.body) or {
return ctx.bad_request('Invalid request body: ${err}')
}
+114
View File
@@ -0,0 +1,114 @@
# uSockets Backend for V-Hono
High-performance server backend using [uSockets](https://github.com/uNetworking/uSockets) library.
## High Concurrency Performance
The included `libusockets_full.a` has been optimized with **backlog=16384** to support high concurrency:
| Concurrent | RPS | Success Rate |
|------------|-----|--------------|
| 4,000 | 112,614 | 100% |
| 6,000 | 56,728 | 100% |
| 8,000 | 33,255 | 100% |
| 10,000 | 25,964 | 100% |
### System Requirements
For 10,000+ concurrent connections:
```bash
# macOS
sudo sysctl -w kern.ipc.somaxconn=8192
ulimit -n 65535
# Linux
sudo sysctl -w net.core.somaxconn=8192
ulimit -n 65535
```
## Performance
Based on benchmark tests (200 connections, 100K requests):
| Backend | RPS | Avg Latency | P95 | P99 |
|---------|-----|-------------|-----|-----|
| 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.**
## Usage
```v
import meiseayoung.hono
fn main() {
mut app := hono.Hono.new()
app.get('/', fn (mut c hono.Context) http.Response {
return c.text('Hello from uSockets!')
})
// Use uSockets backend
app.listen_usockets(3000)
}
```
## Build Command
```bash
v -enable-globals -cc gcc -ldflags "-ldbghelp" your_app.v -o app.exe
```
**Required flags:**
- `-enable-globals` - Required for uSockets global state
- `-cc gcc` - Use GCC compiler (MinGW-w64 on Windows)
- `-ldflags "-ldbghelp"` - Fix Windows linking (Windows only)
## Prerequisites (Windows)
1. **GCC (MinGW-w64)**
```powershell
scoop install mingw
# or
choco install mingw
```
2. **V Compiler** (0.4.x or later)
```powershell
scoop install vlang
```
## Directory Structure
```
usockets/
├── include/ # Header files
│ ├── libusockets.h # uSockets API
│ ├── uv.h # libuv API
│ └── uv/ # libuv headers
├── lib/ # Pre-compiled libraries
│ ├── libusockets_full.a # uSockets + libuv (main)
│ ├── libuv.a # libuv static lib
│ └── ...
└── usockets.v # V bindings
```
## Configuration
```v
// Custom configuration
app.listen_usockets_with_config(meiseayoung.hono.UsocketsConfig{
port: 8080
host: '0.0.0.0'
keepalive_timeout: 30
max_keepalive_req: 10000
})
```
## Notes
- On Windows, uSockets and picoev have similar performance
- On Linux, uSockets may have greater advantages due to epoll optimization
- uSockets excels under high concurrency (200+ connections)
+55
View File
@@ -0,0 +1,55 @@
#!/bin/bash
# uSockets 编译脚本
# 用于重新编译 libusockets_full.a
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
USOCKETS_DIR="/tmp/uSockets"
echo "=== uSockets 编译脚本 ==="
# 检查是否有 uSockets 源码
if [ ! -d "$USOCKETS_DIR" ]; then
echo "克隆 uSockets..."
git clone --depth 1 https://github.com/uNetworking/uSockets.git "$USOCKETS_DIR"
fi
# 应用 backlog 修改
echo "应用 backlog=16384 修改..."
if [ -f "$SCRIPT_DIR/src/bsd.c" ]; then
cp "$SCRIPT_DIR/src/bsd.c" "$USOCKETS_DIR/src/bsd.c"
else
# 如果没有本地修改的源码,直接修改
sed -i.bak 's/listen(listenFd, 512)/listen(listenFd, 16384)/g' "$USOCKETS_DIR/src/bsd.c"
fi
# 编译
echo "编译 uSockets..."
cd "$USOCKETS_DIR"
make clean
# 根据系统选择编译参数
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS
if [[ $(uname -m) == "arm64" ]]; then
# Apple Silicon
WITH_LIBUV=1 CFLAGS="-I/opt/homebrew/include" make
else
# Intel Mac
WITH_LIBUV=1 CFLAGS="-I/usr/local/include" make
fi
else
# Linux
WITH_LIBUV=1 make
fi
# 复制到 v-hono
echo "复制库文件..."
cp "$USOCKETS_DIR/uSockets.a" "$SCRIPT_DIR/../lib/libusockets_full.a"
echo "=== 编译完成 ==="
echo "库文件: $SCRIPT_DIR/../lib/libusockets_full.a"
echo ""
echo "重新编译 v-hono 应用:"
echo " v -enable-globals -prod -o your_app your_app.v"
+353
View File
@@ -0,0 +1,353 @@
/*
* Authored by Alex Hultman, 2018-2019.
* Intellectual property of third-party.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIBUSOCKETS_H
#define LIBUSOCKETS_H
/* 512kb shared receive buffer */
#ifndef LIBUS_RECV_BUFFER_LENGTH
#define LIBUS_RECV_BUFFER_LENGTH 524288
#endif
/* A timeout granularity of 4 seconds means give or take 4 seconds from set timeout */
#define LIBUS_TIMEOUT_GRANULARITY 4
/* 32 byte padding of receive buffer ends */
#define LIBUS_RECV_BUFFER_PADDING 32
/* Guaranteed alignment of extension memory */
#define LIBUS_EXT_ALIGNMENT 16
/* Define what a socket descriptor is based on platform */
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <winsock2.h>
#define LIBUS_SOCKET_DESCRIPTOR SOCKET
#else
#define LIBUS_SOCKET_DESCRIPTOR int
#endif
#ifdef __cplusplus
extern "C" {
#endif
enum {
/* No meaning, default listen option */
LIBUS_LISTEN_DEFAULT,
/* We exclusively own this port, do not share it */
LIBUS_LISTEN_EXCLUSIVE_PORT
};
/* Library types publicly available */
struct us_socket_t;
struct us_timer_t;
struct us_socket_context_t;
struct us_loop_t;
struct us_poll_t;
struct us_udp_socket_t;
struct us_udp_packet_buffer_t;
/* Extra for io_uring */
char *us_socket_send_buffer(int ssl, struct us_socket_t *s);
/* Public interface for UDP sockets */
/* Peeks data and length of UDP payload */
char *us_udp_packet_buffer_payload(struct us_udp_packet_buffer_t *buf, int index);
int us_udp_packet_buffer_payload_length(struct us_udp_packet_buffer_t *buf, int index);
/* Copies out local (received destination) ip (4 or 16 bytes) of received packet */
int us_udp_packet_buffer_local_ip(struct us_udp_packet_buffer_t *buf, int index, char *ip);
/* Get the bound port in host byte order */
int us_udp_socket_bound_port(struct us_udp_socket_t *s);
/* Peeks peer addr (sockaddr) of received packet */
char *us_udp_packet_buffer_peer(struct us_udp_packet_buffer_t *buf, int index);
/* Peeks ECN of received packet */
int us_udp_packet_buffer_ecn(struct us_udp_packet_buffer_t *buf, int index);
/* Receives a set of packets into specified packet buffer */
int us_udp_socket_receive(struct us_udp_socket_t *s, struct us_udp_packet_buffer_t *buf);
void us_udp_buffer_set_packet_payload(struct us_udp_packet_buffer_t *send_buf, int index, int offset, void *payload, int length, void *peer_addr);
int us_udp_socket_send(struct us_udp_socket_t *s, struct us_udp_packet_buffer_t *buf, int num);
/* Allocates a packet buffer that is reuable per thread. Mutated by us_udp_socket_receive. */
struct us_udp_packet_buffer_t *us_create_udp_packet_buffer();
/* Creates a (heavy-weight) UDP socket with a user space ring buffer. Again, this one is heavy weight and
* shoud be reused. One entire QUIC server can be implemented using only one single UDP socket so weight
* is not a concern as is the case for TCP sockets which are 1-to-1 with TCP connections. */
//struct us_udp_socket_t *us_create_udp_socket(struct us_loop_t *loop, void (*read_cb)(struct us_udp_socket_t *), unsigned short port);
//struct us_udp_socket_t *us_create_udp_socket(struct us_loop_t *loop, void (*data_cb)(struct us_udp_socket_t *, struct us_udp_packet_buffer_t *, int), void (*drain_cb)(struct us_udp_socket_t *), char *host, unsigned short port);
struct us_udp_socket_t *us_create_udp_socket(struct us_loop_t *loop, struct us_udp_packet_buffer_t *buf, void (*data_cb)(struct us_udp_socket_t *, struct us_udp_packet_buffer_t *, int), void (*drain_cb)(struct us_udp_socket_t *), const char *host, unsigned short port, void *user);
/* This one is ugly, should be ext! not user */
void *us_udp_socket_user(struct us_udp_socket_t *s);
/* Binds the UDP socket to an interface and port */
int us_udp_socket_bind(struct us_udp_socket_t *s, const char *hostname, unsigned int port);
/* Public interfaces for timers */
/* Create a new high precision, low performance timer. May fail and return null */
struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough, unsigned int ext_size);
/* Returns user data extension for this timer */
void *us_timer_ext(struct us_timer_t *timer);
/* */
void us_timer_close(struct us_timer_t *timer);
/* Arm a timer with a delay from now and eventually a repeat delay.
* Specify 0 as repeat delay to disable repeating. Specify both 0 to disarm. */
void us_timer_set(struct us_timer_t *timer, void (*cb)(struct us_timer_t *t), int ms, int repeat_ms);
/* Returns the loop for this timer */
struct us_loop_t *us_timer_loop(struct us_timer_t *t);
/* Public interfaces for contexts */
struct us_socket_context_options_t {
const char *key_file_name;
const char *cert_file_name;
const char *passphrase;
const char *dh_params_file_name;
const char *ca_file_name;
const char *ssl_ciphers;
int ssl_prefer_low_memory_usage; /* Todo: rename to prefer_low_memory_usage and apply for TCP as well */
};
/* Return 15-bit timestamp for this context */
unsigned short us_socket_context_timestamp(int ssl, struct us_socket_context_t *context);
/* Adds SNI domain and cert in asn1 format */
void us_socket_context_add_server_name(int ssl, struct us_socket_context_t *context, const char *hostname_pattern, struct us_socket_context_options_t options, void *user);
void us_socket_context_remove_server_name(int ssl, struct us_socket_context_t *context, const char *hostname_pattern);
void us_socket_context_on_server_name(int ssl, struct us_socket_context_t *context, void (*cb)(struct us_socket_context_t *, const char *hostname));
void *us_socket_server_name_userdata(int ssl, struct us_socket_t *s);
void *us_socket_context_find_server_name_userdata(int ssl, struct us_socket_context_t *context, const char *hostname_pattern);
/* Returns the underlying SSL native handle, such as SSL_CTX or nullptr */
void *us_socket_context_get_native_handle(int ssl, struct us_socket_context_t *context);
/* A socket context holds shared callbacks and user data extension for associated sockets */
struct us_socket_context_t *us_create_socket_context(int ssl, struct us_loop_t *loop,
int ext_size, struct us_socket_context_options_t options);
/* Delete resources allocated at creation time. */
void us_socket_context_free(int ssl, struct us_socket_context_t *context);
/* Setters of various async callbacks */
void us_socket_context_on_pre_open(int ssl, struct us_socket_context_t *context,
LIBUS_SOCKET_DESCRIPTOR (*on_pre_open)(struct us_socket_context_t *context, LIBUS_SOCKET_DESCRIPTOR fd));
void us_socket_context_on_open(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_open)(struct us_socket_t *s, int is_client, char *ip, int ip_length));
void us_socket_context_on_close(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_close)(struct us_socket_t *s, int code, void *reason));
void us_socket_context_on_data(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_data)(struct us_socket_t *s, char *data, int length));
void us_socket_context_on_writable(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_writable)(struct us_socket_t *s));
void us_socket_context_on_timeout(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_timeout)(struct us_socket_t *s));
void us_socket_context_on_long_timeout(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_timeout)(struct us_socket_t *s));
/* This one is only used for when a connecting socket fails in a late stage. */
void us_socket_context_on_connect_error(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_connect_error)(struct us_socket_t *s, int code));
/* Emitted when a socket has been half-closed */
void us_socket_context_on_end(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_end)(struct us_socket_t *s));
/* Returns user data extension for this socket context */
void *us_socket_context_ext(int ssl, struct us_socket_context_t *context);
/* Closes all open sockets, including listen sockets. Does not invalidate the socket context. */
void us_socket_context_close(int ssl, struct us_socket_context_t *context);
/* Listen for connections. Acts as the main driving cog in a server. Will call set async callbacks. */
struct us_listen_socket_t *us_socket_context_listen(int ssl, struct us_socket_context_t *context,
const char *host, int port, int options, int socket_ext_size);
struct us_listen_socket_t *us_socket_context_listen_unix(int ssl, struct us_socket_context_t *context,
const char *path, int options, int socket_ext_size);
/* listen_socket.c/.h */
void us_listen_socket_close(int ssl, struct us_listen_socket_t *ls);
/* Adopt a socket which was accepted either internally, or from another accept() outside libusockets */
struct us_socket_t *us_adopt_accepted_socket(int ssl, struct us_socket_context_t *context, LIBUS_SOCKET_DESCRIPTOR client_fd,
unsigned int socket_ext_size, char *addr_ip, int addr_ip_length);
/* Land in on_open or on_connection_error or return null or return socket */
struct us_socket_t *us_socket_context_connect(int ssl, struct us_socket_context_t *context,
const char *host, int port, const char *source_host, int options, int socket_ext_size);
struct us_socket_t *us_socket_context_connect_unix(int ssl, struct us_socket_context_t *context,
const char *server_path, int options, int socket_ext_size);
/* Is this socket established? Can be used to check if a connecting socket has fired the on_open event yet.
* Can also be used to determine if a socket is a listen_socket or not, but you probably know that already. */
int us_socket_is_established(int ssl, struct us_socket_t *s);
/* Cancel a connecting socket. Can be used together with us_socket_timeout to limit connection times.
* Entirely destroys the socket - this function works like us_socket_close but does not trigger on_close event since
* you never got the on_open event first. */
struct us_socket_t *us_socket_close_connecting(int ssl, struct us_socket_t *s);
/* Returns the loop for this socket context. */
struct us_loop_t *us_socket_context_loop(int ssl, struct us_socket_context_t *context);
/* Invalidates passed socket, returning a new resized socket which belongs to a different socket context.
* Used mainly for "socket upgrades" such as when transitioning from HTTP to WebSocket. */
struct us_socket_t *us_socket_context_adopt_socket(int ssl, struct us_socket_context_t *context, struct us_socket_t *s, int ext_size);
/* Create a child socket context which acts much like its own socket context with its own callbacks yet still relies on the
* parent socket context for some shared resources. Child socket contexts should be used together with socket adoptions and nothing else. */
struct us_socket_context_t *us_create_child_socket_context(int ssl, struct us_socket_context_t *context, int context_ext_size);
/* Public interfaces for loops */
/* Returns a new event loop with user data extension */
struct us_loop_t *us_create_loop(void *hint, void (*wakeup_cb)(struct us_loop_t *loop),
void (*pre_cb)(struct us_loop_t *loop), void (*post_cb)(struct us_loop_t *loop), unsigned int ext_size);
/* Frees the loop immediately */
void us_loop_free(struct us_loop_t *loop);
/* Returns the loop user data extension */
void *us_loop_ext(struct us_loop_t *loop);
/* Blocks the calling thread and drives the event loop until no more non-fallthrough polls are scheduled */
void us_loop_run(struct us_loop_t *loop);
/* Signals the loop from any thread to wake up and execute its wakeup handler from the loop's own running thread.
* This is the only fully thread-safe function and serves as the basis for thread safety */
void us_wakeup_loop(struct us_loop_t *loop);
/* Hook up timers in existing loop */
void us_loop_integrate(struct us_loop_t *loop);
/* Returns the loop iteration number */
long long us_loop_iteration_number(struct us_loop_t *loop);
/* Public interfaces for polls */
/* A fallthrough poll does not keep the loop running, it falls through */
struct us_poll_t *us_create_poll(struct us_loop_t *loop, int fallthrough, unsigned int ext_size);
/* After stopping a poll you must manually free the memory */
void us_poll_free(struct us_poll_t *p, struct us_loop_t *loop);
/* Associate this poll with a socket descriptor and poll type */
void us_poll_init(struct us_poll_t *p, LIBUS_SOCKET_DESCRIPTOR fd, int poll_type);
/* Start, change and stop polling for events */
void us_poll_start(struct us_poll_t *p, struct us_loop_t *loop, int events);
void us_poll_change(struct us_poll_t *p, struct us_loop_t *loop, int events);
void us_poll_stop(struct us_poll_t *p, struct us_loop_t *loop);
/* Return what events we are polling for */
int us_poll_events(struct us_poll_t *p);
/* Returns the user data extension of this poll */
void *us_poll_ext(struct us_poll_t *p);
/* Get associated socket descriptor from a poll */
LIBUS_SOCKET_DESCRIPTOR us_poll_fd(struct us_poll_t *p);
/* Resize an active poll */
struct us_poll_t *us_poll_resize(struct us_poll_t *p, struct us_loop_t *loop, unsigned int ext_size);
/* Public interfaces for sockets */
/* Returns the underlying native handle for a socket, such as SSL or file descriptor.
* In the case of file descriptor, the value of pointer is fd. */
void *us_socket_get_native_handle(int ssl, struct us_socket_t *s);
/* Write up to length bytes of data. Returns actual bytes written.
* Will call the on_writable callback of active socket context on failure to write everything off in one go.
* Set hint msg_more if you have more immediate data to write. */
int us_socket_write(int ssl, struct us_socket_t *s, const char *data, int length, int msg_more);
/* Special path for non-SSL sockets. Used to send header and payload in one go. Works like us_socket_write. */
int us_socket_write2(int ssl, struct us_socket_t *s, const char *header, int header_length, const char *payload, int payload_length);
/* Set a low precision, high performance timer on a socket. A socket can only have one single active timer
* at any given point in time. Will remove any such pre set timer */
void us_socket_timeout(int ssl, struct us_socket_t *s, unsigned int seconds);
/* Set a low precision, high performance timer on a socket. Suitable for per-minute precision. */
void us_socket_long_timeout(int ssl, struct us_socket_t *s, unsigned int minutes);
/* Return the user data extension of this socket */
void *us_socket_ext(int ssl, struct us_socket_t *s);
/* Return the socket context of this socket */
struct us_socket_context_t *us_socket_context(int ssl, struct us_socket_t *s);
/* Withdraw any msg_more status and flush any pending data */
void us_socket_flush(int ssl, struct us_socket_t *s);
/* Shuts down the connection by sending FIN and/or close_notify */
void us_socket_shutdown(int ssl, struct us_socket_t *s);
/* Shuts down the connection in terms of read, meaning next event loop
* iteration will catch the socket being closed. Can be used to defer closing
* to next event loop iteration. */
void us_socket_shutdown_read(int ssl, struct us_socket_t *s);
/* Returns whether the socket has been shut down or not */
int us_socket_is_shut_down(int ssl, struct us_socket_t *s);
/* Returns whether this socket has been closed. Only valid if memory has not yet been released. */
int us_socket_is_closed(int ssl, struct us_socket_t *s);
/* Immediately closes the socket */
struct us_socket_t *us_socket_close(int ssl, struct us_socket_t *s, int code, void *reason);
/* Returns local port or -1 on failure. */
int us_socket_local_port(int ssl, struct us_socket_t *s);
/* Returns remote ephemeral port or -1 on failure. */
int us_socket_remote_port(int ssl, struct us_socket_t *s);
/* Copy remote (IP) address of socket, or fail with zero length. */
void us_socket_remote_address(int ssl, struct us_socket_t *s, char *buf, int *length);
#ifdef __cplusplus
}
#endif
/* Decide what eventing system to use by default */
#if !defined(LIBUS_USE_IO_URING) && !defined(LIBUS_USE_EPOLL) && !defined(LIBUS_USE_LIBUV) && !defined(LIBUS_USE_GCD) && !defined(LIBUS_USE_KQUEUE) && !defined(LIBUS_USE_ASIO)
#if defined(_WIN32)
#define LIBUS_USE_LIBUV
#elif defined(__APPLE__) || defined(__FreeBSD__)
#define LIBUS_USE_KQUEUE
#else
#define LIBUS_USE_EPOLL
#endif
#endif
#endif // LIBUSOCKETS_H
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef UV_AIX_H
#define UV_AIX_H
#define UV_PLATFORM_LOOP_FIELDS \
int fs_fd; \
#define UV_PLATFORM_FS_EVENT_FIELDS \
uv__io_t event_watcher; \
char *dir_filename; \
#endif /* UV_AIX_H */

Some files were not shown because too many files have changed in this diff Show More