这个项目能做什么

# Go REST Client 库 本项目提供了一个 Go 库和命令行工具,用于执行 `.http` 文件中定义的 HTTP 请求,该格式由 JetBrains IDE 和 VS Code REST Client 扩展推广。它旨在与这些工具完全兼容,使开发者能够在 IDE 中进行手动测试和在 Go 中进行自动化端到端(E2E)测试时使用相同的请求文件。 ## 主要特性 - **JetBrains/VS Code 兼容**:使用与流行 IDE 扩展相同的语法、变量和行为解析 `.http` 文件。 - **变量替换**:支持自定义变量、环境变量以及系统变量,如 `{{$guid}}`、`{{$randomInt}}`、`{{$timestamp}}` 和 `{{$datetime}}`。 - **响应链式引用**:引用同一文件中其他请求的响应,例如 `{{authenticate.response.body.token}}`。 - **请求引用**:使用 `@ref`(每次运行缓存)或 `@forceRef`(始终重新执行)来运行前置请求,使用 `@import` 在文件之间共享命名请求。 - **请求控制**:使用 `@disabled` 跳过请求,使用 `@sleep <ms>` 在发送前暂停,使用 `@loop` 循环请求。 - **响应验证**:将响应与 `.hresp` 文件进行比较,支持 `{{$any}}`、`{{$regexp}}` 和 `{{$anyGuid}}` 等占位符。 - **每个文件多个请求**:使用 `###` 分隔请求。 - **E2E 测试就绪**:专为自动化集成测试设计。 ## HTTP 文件格式 `.http` 文件是定义 HTTP 请求的纯文本文件。一个请求由可选的名称、方法、URL、标头和正文组成。 ```http ### Request Name METHOD URL Header1: value1 body content ``` ### 示例 ```http @baseUrl = https://api.example.com @userId = 123 ### Get user profile GET {{baseUrl}}/users/{{userId}} Authorization: Bearer {{authToken}} X-Request-ID: {{$guid}} ``` ## 库用法 ### 安装 ```bash go get github.com/bmcszk/go-restclient ``` ### 在 Go 中执行请求 ```go package main import ( "context" "log" "github.com/bmcszk/go-restclient" ) func main() { client, _ := restclient.NewClient( restclient.WithVars(map[string]interface{}{ "authToken": "your-token-here", }), ) responses, _ := client.ExecuteFile(context.Background(), "requests.http") for i, resp := range responses { if resp.Error != nil { log.Printf("Request %d failed: %v", i+1, resp.Error) } else { log.Printf("Request %d: %d %s", i+1, resp.StatusCode, resp.Status) } } } ``` ### 客户端选项 ```go client, err := restclient.NewClient( restclient.WithBaseURL("https://api.example.com"), restclient.WithDefaultHeader("X-API-Key", "secret"), restclient.WithHTTPClient(customHTTPClient), restclient.WithVars(variables), ) ``` ## CLI 用法 `restclient` CLI 从命令行运行 `.http` 文件。 ### 安装 ```bash go install github.com/bmcszk/go-restclient/cmd/restclient@latest ``` ### 基本命令 ```bash restclient -f requests.http --all restclient -f requests.http -n "get user" restclient -f requests.http -i 0 restclient --version ``` ### 列出请求 ```bash restclient -f requests.http --list ``` ### 运行单个请求 按名称(不区分大小写): ```bash restclient -f requests.http -n "create user" ``` 按从 0 开始的索引: ```bash restclient -f requests.http -i 0 ``` ### 命令行变量 ```bash restclient -f requests.http -D token=abc123 -D env=prod ``` ### 前置请求 ```bash restclient -f requests.http -n "get protected" -A authenticate ``` ### 出错时失败 在 HTTP 4xx/5xx 响应时以代码 1 退出: ```bash restclient -f requests.http -E ``` ### 输出格式 ```bash # Body only restclient -f requests.http -o body # JSON path extraction restclient -f requests.http -o jsonpath "data.users[0].name" # Environment variable format restclient -f requests.http -o env "token" ``` ### CLI 标志 | 短 | 长 | 描述 | | ----- | ---- | ----------- | | `-f` | `--file` | 请求文件路径(必需) | | `-n` | `--name` | 按名称运行请求 | | `-i` | `--index` | 按索引运行请求 | | | `--all` | 运行文件中的所有请求 | | `-e` | `--expected` | 预期响应文件 | | | `--e-name` | 预期响应名称 | | | `--e-index` | 预期响应索引 | | `-l` | `--list` | 列出请求 | | `-E` | `--fail-on-error` | 在 4xx/5xx 时失败 | | `-o` | `--output` | 输出格式 | | `-A` | `--after` | 前置请求 | | `-D` | `--define` | 定义变量(可重复) | ## 响应验证 创建 `.hresp` 文件以验证响应。 **responses.hresp:** ```http HTTP/1.1 200 OK Content-Type: application/json { "id": "{{$anyGuid}}", "name": "{{$any}}", "createdAt": "{{$anyTimestamp}}" } ``` **在 Go 中验证:** ```go err := client.ValidateResponses("responses.hresp", responses...) if err != nil { log.Fatal("Validation failed:", err) } ``` ### 验证占位符 - `{{$any}}` - 匹配任意文本 - `{{$regexp ``pattern``}}` - 正则表达式模式(位于反引号中) - `{{$anyGuid}}` - UUID 格式 - `{{$anyTimestamp}}` - Unix 时间戳 - `{{$anyDatetime 'format'}}` - 日期时间(rfc1123、iso8601 或自定义) ## 使用场景 ### 手动测试 在开发过程中使用你喜欢的 IDE 扩展来测试 API。 ### 自动化 E2E 测试 ```go func TestUserAPI(t *testing.T) { client, _ := restclient.NewClient( restclient.WithBaseURL(testServer.URL), ) responses, err := client.ExecuteFile(context.Background(), "user_tests.http") require.NoError(t, err) err = client.ValidateResponses("user_expected.hresp", responses...) require.NoError(t, err) } ``` ## 开发 ### 先决条件 - Go 1.21+ ### 命令 ```bash make check # Run all checks (lint, test, build) ``` ## 许可证 MIT License