纯 Nim 实现的 SSE HTTP 客户端,从零构建 TCP + TLS,零第三方依赖。
- 零第三方依赖 — 仅用 Nim 标准库
- 从零构建 — 基于
net.Socket实现 TCP/TLS,手动解析 HTTP/1.1 - HTTPS 支持 — 通过标准库
net的 SSL 上下文,支持证书验证开关 - SSE 流式传输 — 增量式 Server-Sent Events 解析器
- jQuery 风格链式 API —
client("url").get().then(...).catch(...) - Sync + Async 双模式 — 同步阻塞与异步非阻塞 API,均支持 HTTPS
- 应用层超时控制 — 连接、发送、接收均有独立超时
nimble installimport sse_nim_http_client
# 同步 GET
let res = client("https://api.example.com/data").get()
res.then(proc (r: Response) =
echo r.status # 200
echo r.text() # body text
).catch(proc (e: ref Exception) =
echo e.msg
)
# 链式 POST JSON
client("https://api.example.com/users")
.header("Authorization", "Bearer xxx")
.post("""{"name":"nim"}""", "application/json")
.then(proc (r: Response) =
echo r.json()["id"]
)
# SSE 流式监听
client("https://api.example.com/events")
.sse(proc (ev: SseEvent) =
echo ev.event, ": ", ev.data
)import std/asyncdispatch
import sse_nim_http_client
proc main() {.async.} =
let res = await client("https://api.example.com/data")
.timeout(5000)
.getAsync()
echo res.status
echo res.text()
waitFor main()# 同步:连接、发送、接收均受 timeout 控制
client("https://api.example.com/data")
.timeout(5000) # 5 秒超时
.get()
# 异步:同样支持
await client("https://api.example.com/data")
.timeout(5000)
.getAsync()client("https://self-signed.local")
.insecure() # 跳过 HTTPS 证书验证
.get()src/
├── sse_nim_http_client.nim # 主入口 / jQuery 风格 API
├── core/
│ ├── url.nim # URL 解析
│ ├── connection.nim # TCP 连接(含超时)
│ └── request.nim # HTTP 请求构建
├── protocols/
│ └── http11.nim # HTTP/1.1 响应解析(含 chunked)
├── streaming/
│ └── sse.nim # SSE 增量解析
└── ssl/
└── openssl.nim # TLS/SSL 封装
# 需要 -d:ssl 启用 HTTPS 支持
nim c -d:ssl your_app.nimnimble testMIT