Skip to content

Latest commit

 

History

History
120 lines (93 loc) · 2.56 KB

File metadata and controls

120 lines (93 loc) · 2.56 KB

SseNimHttpClient

纯 Nim 实现的 SSE HTTP 客户端,从零构建 TCP + TLS,零第三方依赖。

特性

  • 零第三方依赖 — 仅用 Nim 标准库
  • 从零构建 — 基于 net.Socket 实现 TCP/TLS,手动解析 HTTP/1.1
  • HTTPS 支持 — 通过标准库 net 的 SSL 上下文,支持证书验证开关
  • SSE 流式传输 — 增量式 Server-Sent Events 解析器
  • jQuery 风格链式 APIclient("url").get().then(...).catch(...)
  • Sync + Async 双模式 — 同步阻塞与异步非阻塞 API,均支持 HTTPS
  • 应用层超时控制 — 连接、发送、接收均有独立超时

安装

nimble install

快速开始

import 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
  )

异步 HTTPS

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.nim

测试

nimble test

许可证

MIT