Skip to content

Latest commit

 

History

History
402 lines (315 loc) · 14.5 KB

api-reference.md

File metadata and controls

402 lines (315 loc) · 14.5 KB

API 参考(API Reference)

request-mock-skills 全量 API 文档。pkg/mock 是 SDK 入口。 最近更新:2026-07-04

类型

RequestSpec — 请求参数模型

type RequestSpec struct {
    Method            string            // HTTP 方法,空默认 GET
    URL               string            // 请求 URL(必填)
    HTTPVersion       string            // 空→默认 HTTP/1.1
    Headers           map[string]string // 请求头
    Cookies           map[string]string // 请求 Cookie
    Query             map[string]string // URL 查询参数
    PostMIME          string            // 请求体 MIME
    PostText          string            // 原始请求体(与 PostParams 二选一,优先)
    PostParams        map[string]string // 表单参数
    ResponseStatus    int               // 响应状态码
    ResponseStatusText string
    ResponseHeaders   map[string]string
    ResponseCookies   map[string]string // 响应 Set-Cookie
    ResponseBody      string
    ResponseMIME      string
    ResponseSize      int               // 响应体字节数,>0 显式设置
    ServerIP          string
    Connection        string            // 连接 ID
    Pageref           string            // 关联页面 ID
    Priority          string            // Chrome 扩展:优先级
    ResourceType      string            // Chrome 扩展:资源类型
    Comment           string
    StartedDateTime   string            // RFC3339,空→自动填
    Timings           Timings
}

Timings

type Timings struct {
    Blocked, DNS, Connect, Send, Wait, Receive, SSL float64 // 毫秒
}

Spec groups — 100+ 可配置维度

RequestSpec 持有 9 个功能分组,覆盖完整 HAR 规范 + Chrome DevTools 扩展字段。分组优先级高于扁平字段(同名维度同时设置时分组胜出)。

分组字段 类型 覆盖维度
Request *RequestGroup HTTPVersion、HeadersSize、BodySize、scheme/host/port/path/fragment、Basic auth(user/pass)、Fragments、Comment
Response *ResponseGroup HTTPVersion、RedirectURL、HeadersSize、BodySize、TransferSize、Compression、Encoding、Error、Comment
Cache *CacheGroup beforeRequest / afterRequest(expires、lastAccess、ETag、hitCount、Comment)
Timing *TimingGroup blocked/dns/connect/send/wait/receive/ssl + Chrome _blocked_queueing/_blocked_proxy、Comment
CookiesGroup *CookieGroup 请求/响应 Cookie 详细属性(path/domain/expires/httpOnly/secure/sameSite)
PostData *PostDataGroup MimeType、Text、Params(带 fileName/contentType)
Meta *MetaGroup ServerIPAddress、Connection、Pageref、Priority、ResourceType、time、startedDateTime、Comment
Initiator *InitiatorGroup type、url、lineNumber、stack callFrames
—(顶级) PageGroup HAR Log.Pages:id、title、startedDateTime、pageTimings(onContentLoad/onLoad)、Comment。注:PageGroup 是顶级对象,不挂 RequestSpec,用于维度计数与未来 WithPages 增强

示例:

spec := mock.RequestSpec{
    Method: "GET", URL: "https://api.example.com/x",
    Cache: &mock.CacheGroup{
        BeforeRequest: &mock.CacheEntry{ETag: "w-1", HitCount: 2, Expires: "2026-12-31T00:00:00Z"},
    },
    Timing: &mock.TimingGroup{DNS: 10, BlockedQueueing: 5, BlockedProxy: 3},
    Meta:   &mock.MetaGroup{Priority: "High", ResourceType: "xhr"},
}

Generator — 确定性批量生成器

g := mock.NewGenerator(seed int64, opts ...GeneratorOption) *Generator
g.Seed() int64
g.GenerateSpecs(base RequestSpec, n int, transforms ...Transform) []RequestSpec
g.GenerateSpecsBatch(bases []RequestSpec, n int, transforms ...Transform) []RequestSpec
g.GenerateN(base RequestSpec, n int, transforms ...Transform) (*har.Har, error)
g.GenerateNFromSpecs(specs []RequestSpec) (*har.Har, error)

Transform — 变换函数

type Transform func(spec *RequestSpec, i int, r *rand.Rand)

Format — 导出格式

curl · wget · python · postman · xml · yaml · har/json · jsonl · csv · markdown · html · text

Result — JSON 结果信封

type Result struct {
    OK     bool   `json:"ok"`
    Count  int    `json:"count,omitempty"`
    Seed   int64  `json:"seed,omitempty"`
    Format string `json:"format,omitempty"`
    Data   string `json:"data,omitempty"`
    Error  string `json:"error,omitempty"`
}

Config / ExportConfig / TemplateRef / PageSpec / SplitMode

见下方各章节。

生成 API

函数 说明
Generate(specs, opts...) (*har.Har, error) 多条 spec → HAR
GenerateOne(spec, opts...) (*har.Har, error) 单条
MustGenerate(specs, opts...) *har.Har panic 版

GenerateOption

  • WithCreator(name, version)
  • WithBrowser(name, version)
  • WithHTTPVersion(v)
  • WithIndent(bool) — 影响生成配置(导出缩进建议用 WithExportIndent)
  • WithPages(pages ...PageSpec) — 声明页面分组

GeneratorOption

  • WithGeneratorCreator(name, version)

导出 API

函数 说明
Export(h, format) (string, error) 基础导出
ExportWithOpts(h, format, opts...) (string, error) 支持导出选项
ExportBytes(h, format, opts...) ([]byte, error) 字节版
ExportToFile(h, format, path, opts...) error 导出到文件(自动建目录)
ExportString(h, format) (string, error) Export 别名
MustExport(h, format) string panic 版

ExportOption

  • WithExportIndent(bool) — 控制 json/har 缩进(默认 true)

一步到位 API(SDK 推荐)

函数 说明
GenerateAndExport(specs, format, opts...) (string, *har.Har, error) 多条一步导出
GenerateOneAndExport(spec, format, opts...) (string, *har.Har, error) 单条
GenerateNAndExport(seed, base, n, format, transforms...) (string, *har.Har, error) 批量一步
GenerateNAndExportToFile(seed, base, n, format, path, transforms...) error 批量直接到文件
SpecsFromSeed(seed, base, n, transforms...) []RequestSpec 仅产出 specs

拆分 API

mock.Split(h *har.Har, mode SplitMode, opts ...SplitOption) (map[string]*har.Har, error)
mock.SplitModes() []SplitMode

SplitMode

page · domain · status · method · size · time

SplitOption

  • WithSplitSize(maxEntries int) — size 模式
  • WithSplitInterval(d time.Duration) — time 模式

变换 API

内置变换(16 个)

名称 函数 行为
server_ip RandomServerIP 随机服务器 IP
user_agent RandomUserAgent 随机 UA
path RandomPath 追加随机路径段
query_noise RandomQueryNoise 注入随机查询参数
status RandomStatus 随机响应状态码(不覆盖已设)
timings RandomTimings 随机各阶段耗时(不覆盖已设)
index IndexSuffix 注入序号参数
port RandomPort 随机 URL 端口
host RandomHost 追加随机子域段
resp_cookie RandomResponseCookie 注入随机响应 Cookie
header RandomHeader 注入随机额外请求头
body_noise RandomBodyNoise JSON body 追加随机字段
seq_status SequentialStatus 按序号轮转状态码
priority RandomPriority 随机优先级
resource_type RandomResourceType 随机资源类型
connection RandomConnection 随机连接 ID
mock.DefaultTransforms        // 默认变换集
mock.NamedTransforms() []string
mock.LookupTransform(name) (Transform, bool)

模板 API

内置模板(20 个)

getjson · postjson · postform · login · upload · bearer delete · put · patch · head · options banner · redirect · error · portscan graphql · sse · websocket · grpcweb · chunked

模板构造函数

GETJSON · POSTJSON · POSTForm · Login · UploadFile · APIWithBearer DELETE · PUT · PATCH · HEAD · OPTIONS BannerResponse · RedirectChain · ErrorPage · PortScanResponse GraphQLQuery · SSEStream · WebSocketHandshake · GRPCWeb · ChunkedTransfer

mock.Templates            // map[name]func() RequestSpec

配置 API

mock.LoadConfig(path string) (*Config, error)        // YAML/JSON 按扩展名
mock.ParseConfig(data []byte, ext string) (*Config, error)
(*Config).Validate() error
(*Config).ResolveSpecs() []RequestSpec
(*Config).ResolveTransforms() []Transform
(*Config).Run() (string, *har.Har, error)            // 一键跑通

Config 字段

type Config struct {
    Seed       int64
    Count      int
    Specs      []RequestSpec
    Templates  []TemplateRef
    Transforms []string
    Export     ExportConfig
}

约定:Transforms: ["none"] 关闭所有变换。

URL 分解重组

当 spec.URL 为空且 RequestGroup 含 scheme/host/port/path/fragment/userinfo 任一字段时, Builder 会自动重组完整 URL,使分解字段真正生效:

spec := mock.RequestSpec{
    Method: "GET",
    Request: &mock.RequestGroup{Scheme: "https", Host: "api.example.com", Port: 8080, Path: "v1/x"},
    // spec.URL 为空 → 重组为 https://api.example.com:8080/v1/x
}
h, _ := mock.GenerateOne(spec)

规则:Scheme 默认 https;443(https)/80(http) 端口省略;Path 自动补 /;userinfo 拼 user:pass@。spec.URL 非空时原样保留,分解字段不干扰。

Channel 流式交付

type StreamItem struct {
    Kind  string      // entry / export / error / done
    Item  interface{} // *har.Entries 或 string
    Err   error
    Index int         // 派生序列序号,从 0 开始
}
type DeliveryMode string // "sync" | "channel"
type StreamOptions struct {
    Format Format // 非空 → 推送导出字符串;空 → 推送 *har.Entries
    Buffer int    // channel 缓冲
}

func (g *Generator) GenerateStream(base RequestSpec, n int, opts StreamOptions, transforms ...Transform) <-chan StreamItem
func (g *Generator) GenerateStreamFromSpecs(specs []RequestSpec, opts StreamOptions) <-chan StreamItem
func CollectStream(ch <-chan StreamItem) ([]StreamItem, error)

生产者在独立 goroutine,消费完关闭 channel。Generator 私有 rand 在该 goroutine 内独占使用(非并发安全但局部)。

统一 Mock 引擎

type Engine struct { /* Config + Generator */ }

func NewEngine(cfg *Config) (*Engine, error)
func MustNewEngine(cfg *Config) *Engine
func (e *Engine) Run() (*har.Har, error)                       // 同步生成
func (e *Engine) RunExport(format Format) (string, *har.Har, error)  // 同步生成+导出
func (e *Engine) RunStream(opts StreamOptions) (<-chan StreamItem, error)  // 流式
func (e *Engine) Config() *Config
func (e *Engine) Seed() int64

Engine 接受 Config 模板,按需返回同步 *har.Har 或流式 Channel。零 seed 默认为 1。 ExportConfig 新增 Delivery 字段(sync/channel),向后兼容(空值即 sync)。

cfg := &mock.Config{
    Seed: 42, Count: 100,
    Specs:      []mock.RequestSpec{{Method: "GET", Request: &mock.RequestGroup{Host: "api.example.com", Path: "/x"}}},
    Transforms: []string{"none"},
}
eng, _ := mock.NewEngine(cfg)
ch, _ := eng.RunStream(mock.StreamOptions{Format: mock.FormatCurl})
for it := range ch {
    if it.Kind == mock.StreamKindExport { fmt.Println(it.Item) }
}

请求链(Request Chain)

多条因果关联请求:前一条响应自动注入后一条请求,生成完整连贯的 HAR。

type LinkType string  // "location" | "header" | "cookie" | "body"
type LinkTarget string // "header" | "query"(仅 body 类型用)

type Link struct {
	Type   LinkType   // 关联方式
	From   string     // 来源:响应头名 / cookie 名 / body 点分 key 或 /regex/
	To     string     // 目标:请求头名 / cookie 名 / query 参数名
	Target LinkTarget // body 类型:注入 header 还是 query
	Prefix string     // 注入值前缀(如 "Bearer ")
}

type ChainStep struct {
	Spec RequestSpec
	Link *Link  // 到下一步的关联,最后一步可空
}

type RequestChain struct{ Steps []ChainStep }

func GenerateChain(chain RequestChain, opts ...GenerateOption) (*har.Har, error)
func (e *Engine) RunChain(chain RequestChain) (*har.Har, error)
func (e *Engine) RunChainExport(chain RequestChain, format Format) (string, *har.Har, error)
func RedirectSequence(startURL string, hops int) RequestChain  // 多跳重定向模板

LinkType 说明

Type From To 行为
location 忽略 忽略 取响应 Location 头作为下一条 URL(相对 URL 自动解析)
header 响应头名 请求头名 响应头值注入下一条请求头
cookie Set-Cookie 名 cookie 名(可空) 响应 cookie 值注入下一条请求 cookie
body 点分 key(data.token)或 /regex/ header 名或 query 名 从响应体提取值注入(Target 决定位置)

YAML 配置

chains:
  - steps:
      - spec:
          method: POST
          url: https://api.example.com/login
          responseBody: '{"data":{"token":"tok"}}'
        link:
          type: body
          from: data.token
          to: Authorization
          target: header
          prefix: "Bearer "
      - spec:
          method: GET
          url: https://api.example.com/me

CLI: request-mock engine -c cfg.yaml --chain chains.yaml -f curl --raw

结果信封 API

mock.NewOKResult(format Format, count int, seed int64, data string) Result
mock.NewErrorResult(err error) Result
(*Result).MarshalJSONString() (string, error)

CLI

命令 说明
generate 按参数构造,支持 -n/--seed/--transform 批量派生
template 内置模板,--list 列出,--name 使用
batch 配置文件驱动批量
split 按维度拆分 HAR 文件
version 版本号

所有命令默认输出结构化 JSON 信封(ok/count/seed/format/data),--raw 输出裸结果,错误走 stderr JSON 且退出码非 0。

与 har-skills 的边界

复用:HAR 类型、AddEntry/AddRequestHeader/AddCookie/AddQueryParameter/SetPostData/SetResponseStatus/SetResponseContentText/SetResponseContent/AddResponseCookie/SetServerIP/SetConnection/SetTimings/AddPage/SetPageref、ToJSON/ToJSONLines/ToCurl/ToWget/ToPythonRequests/ToPostmanCollection/ToXML/ToYAML/Convert、SplitBy*。

不重新实现:HAR 类型与序列化。