httpdumps

package
v2.11.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	MockPrefix   = "/mock"
	MaxMockBody  = 1 << 20 // 1 MB
	MaxMockDelay = 30000   // ms
	// MaxMockRulesPerProject caps the stored rules of one project (rules for
	// every project count as one more project), so a client in a loop cannot
	// fill the database.
	MaxMockRulesPerProject = 500
)
View Source
const (
	// MaxMockRepeat caps the loop items of one render (repeat, and range over
	// queryAll or body), so nested loops stay bounded even when they write
	// nothing. Other loops and recursion are refused at parse time.
	MaxMockRepeat = 10000
	// MaxMockWork caps the steps of one render: each loop item costs the
	// number of steps (actions, commands, text) in the loop's body.
	MaxMockWork = 1_000_000
	// MaxMockGenerated caps the bytes helpers make in one render (fake, json,
	// print…), written out or not.
	MaxMockGenerated = 4 << 20
)
View Source
const MaxMockSentBody = 64 << 10 // 64 KB

MaxMockSentBody caps the response body kept with a captured mock request.

View Source
const (
	// MaxOpenAPISpec caps a spec, uploaded or downloaded.
	MaxOpenAPISpec = 5 << 20
)

Variables

View Source
var MaxMockRenderTime = 2 * time.Second

MaxMockRenderTime bounds one render: what the step and byte budgets do not price (e.g. comparing two 1 MB strings) still stops in time.

View Source
var MockHelpers = []MockHelper{
	{"path", "request", `path "name"`, `Value of a path parameter of the rule's path, as a string. "*" is the rest matched by a trailing *. Missing: "".`,
		`{"id": {{ path "id" }}}`, `rule /users/{id}, request /mock/users/42 → {"id": 42}`},
	{"query", "request", `query "name"`, `First value of a query-string parameter, as a string. Missing: "".`,
		`{"page": {{ query "page" | default "1" }}}`, `?page=3 → {"page": 3}; no page → {"page": 1}`},
	{"queryAll", "request", `queryAll "name"`, `All values of a query-string parameter, as a list of strings.`,
		`{"tags": {{ queryAll "tag" | json }}}`, `?tag=a&tag=b → {"tags": ["a","b"]}`},
	{"header", "request", `header "Name"`, `Value of a request header (name is case-insensitive). Missing: "".`,
		`{"request_id": {{ header "X-Request-Id" | json }}}`, `X-Request-Id: abc → {"request_id": "abc"}`},
	{"body", "request", `body "dot.path"`, `Value from the JSON request body by a dot path; list items by index (items.0.id). Returns the JSON value as is (string, number, bool, object, list); missing or no JSON body: nothing. Use | json to write it.`,
		`{"echo": {{ body "user.email" | json }}}`, `body {"user":{"email":"a@example.com"}} → {"echo": "a@example.com"}`},
	{"bodyRaw", "request", `bodyRaw`, `The request body as a string (first 1 MB).`,
		`{{ bodyRaw }}`, `echoes the body back`},
	{"method", "request", `method`, `Request method: GET, POST, …`,
		`{"method": {{ method | json }}}`, `{"method": "POST"}`},
	{"requestPath", "request", `requestPath`, `Request path without the /mock prefix.`,
		`{"path": {{ requestPath | json }}}`, `/mock/users/42 → {"path": "/users/42"}`},

	{"fake", "fake", `fake "name" [args…]`, `Fake data from gofakeit by generator name (case-insensitive). Arguments fill the generator's parameters in order. Strings need | json in JSON bodies; numbers and bools can be written as is. Objects (e.g. "person") need | json. Full list with parameters: GET /api/mocks/helpers.`,
		`{"name": {{ fake "name" | json }}, "age": {{ fake "number" 18 90 }}}`, `{"name": "Lavina Kuhn", "age": 37}`},
	{"pick", "data", `pick a b c…`, `One of the arguments at random.`,
		`{"status": {{ pick "paid" "pending" "failed" | json }}}`, `{"status": "pending"}`},
	{"repeat", "data", `repeat n`, `A list 0…n-1 for range: repeats a block n times. Inside, $i is the index. range works only over repeat, queryAll and body; all loop items in one response add up to at most 10000, and items × the steps in the loop body to at most 1000000. Helpers may make at most 4 MB per response. define, template and block are not supported.`,
		`[{{ range $i := repeat 3 }}{{ if $i }},{{ end }}{"n": {{ add $i 1 }}}{{ end }}]`, `[{"n": 1},{"n": 2},{"n": 3}]`},
	{"add", "data", `add a b`, `Sum of two integers (use int on request values first).`,
		`{{ add 2 3 }}`, `5`},
	{"int", "data", `int value`, `A request value as an integer: a string ("42", "4.9" → 4), a JSON number from body, a bool (1/0); missing or "" → 0; other text is an error. Request values are strings and body numbers are decimals, so convert them before repeat, add or comparing with a whole number.`,
		`{{ range $i := repeat (int (query "limit" | default "2")) }}{{ $i }}{{ end }} {{ if gt (int (body "qty")) 10 }}bulk{{ end }}`, `?limit=3 → 012; body {"qty": 12} → bulk`},
	{"now", "data", `now ["layout"]`, `Current time, UTC. Default RFC 3339; a Go time layout (e.g. "2006-01-02") or "unix" for seconds.`,
		`{"created_at": {{ now | json }}, "ts": {{ now "unix" }}}`, `{"created_at": "2026-11-07T10:00:00Z", "ts": 1794045600}`},

	{"json", "output", `json value`, `Writes a value as JSON: strings quoted and escaped, lists and objects encoded. Use it for every string in a JSON body.`,
		`{"name": {{ fake "name" | json }}}`, `{"name": "O'Neil \"Jr\""}`},
	{"default", "output", `default fallback value`, `value, or fallback when value is empty ("", missing). Pipe form: value | default fallback.`,
		`{{ query "limit" | default "20" }}`, `no limit → 20`},
	{"upper", "output", `upper s`, `Upper case.`, `{{ upper "abc" }}`, `ABC`},
	{"lower", "output", `lower s`, `Lower case.`, `{{ lower "ABC" }}`, `abc`},
}

MockHelpers is the reference of all template helpers, in reading order.

Functions

This section is empty.

Types

type EventStorer

type EventStorer interface {
	HandleIncoming(ctx context.Context, inc *event.Incoming) error
}

EventStorer stores a captured request (the core EventService).

type MockFake

type MockFake struct {
	Name        string          `json:"name"`
	Category    string          `json:"category"`
	Description string          `json:"description"`
	Example     string          `json:"example"`
	Output      string          `json:"output"`
	Params      []MockFakeParam `json:"params"`
}

MockFake documents one fake generator for `fake "name" …`.

func MockFakes

func MockFakes() []MockFake

MockFakes lists the fake generators templates can use, by category then name.

type MockFakeParam

type MockFakeParam struct {
	Name     string   `json:"name"`
	Type     string   `json:"type"`
	Optional bool     `json:"optional"`
	Default  string   `json:"default,omitempty"`
	Options  []string `json:"options,omitempty"`
}

MockFakeParam is one parameter of a fake generator.

type MockHelper

type MockHelper struct {
	Name        string `json:"name"`
	Group       string `json:"group"` // request, data, output, fake
	Usage       string `json:"usage"`
	Description string `json:"description"`
	Example     string `json:"example"`
	Result      string `json:"result"`
}

MockHelper documents one template helper.

type MockNear

type MockNear struct {
	RuleID   string `json:"rule_id"`
	RuleName string `json:"rule_name"`
	Reason   string `json:"reason"`
}

MockNear is a rule that missed a request by one condition. Reason is "disabled", "method" or "project".

type MockRule

type MockRule struct {
	ID      string            `json:"id"`
	Project string            `json:"project"` // empty = every project
	Name    string            `json:"name"`
	Method  string            `json:"method"` // GET, POST, … or ANY
	Path    string            `json:"path"`   // /users/me, /users/{id}, /files/*
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
	Body    string            `json:"body"`
	DelayMs int               `json:"delay_ms"`
	// Template makes Body and header values Go templates (mock_template.go).
	Template bool `json:"template"`
	// Seed, when not 0, makes a template's fake data the same on every request.
	Seed int64 `json:"seed"`
	// Group names the OpenAPI import that made the rule ("" = none).
	Group     string `json:"group"`
	Enabled   bool   `json:"enabled"`
	Position  int    `json:"position"`
	Source    string `json:"source"`
	ReadOnly  bool   `json:"read_only"`
	CreatedAt string `json:"created_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

MockRule is one mock response. Rules from buggregator.yaml have Source "config" and are read-only; stored rules have Source "api" (UI, REST) or "mcp" (made by an agent through MCP).

func (*MockRule) Normalize

func (r *MockRule) Normalize() error

Normalize fills defaults and validates the rule.

type Module

type Module struct {
	module.BaseModule
	// contains filtered or unexported fields
}

func New

func New(attachments *storage.AttachmentStore, db *sql.DB) *Module

func (*Module) HTTPHandler

func (m *Module) HTTPHandler() module.HTTPIngestionHandler

func (*Module) HandleIncoming

func (m *Module) HandleIncoming(ctx context.Context, inc *event.Incoming) error

HandleIncoming forwards to the event service set later by main (routes are registered before it exists).

func (*Module) Name

func (m *Module) Name() string

func (*Module) OnEventsDeleted

func (m *Module) OnEventsDeleted(uuids []string)

OnEventsDeleted removes the attachment rows of deleted events.

func (*Module) OnInit

func (m *Module) OnInit(db *sql.DB) error

func (*Module) PreviewMapper

func (m *Module) PreviewMapper() event.PreviewMapper

func (*Module) RegisterMCPTools

func (m *Module) RegisterMCPTools(server *sdkmcp.Server)

RegisterMCPTools adds the mock_* tools. The write tools exist only when mcp.mock_write is on (the default).

func (*Module) RegisterMigrations

func (m *Module) RegisterMigrations(migrator *storage.Migrator) error

func (*Module) RegisterProtectedRoutes

func (m *Module) RegisterProtectedRoutes(mux *http.ServeMux, protect func(http.Handler) http.Handler)

RegisterProtectedRoutes adds the mock rule API behind the API auth.

func (*Module) RegisterRoutes

func (m *Module) RegisterRoutes(mux *http.ServeMux, _ event.Store)

RegisterRoutes mounts the mock server under /mock/. It is public: the mocked API's clients call it. The route is more specific than the ingestion pipeline at "/", so no rule can shadow SDK ingestion, /api or the UI.

func (*Module) SetEventService

func (m *Module) SetEventService(es EventStorer)

SetEventService gives the mock server the service that stores captured requests.

func (*Module) SetMCPMockWrite

func (m *Module) SetMCPMockWrite(on bool)

SetMCPMockWrite turns the MCP write tools (create, update, delete, from request) on or off. Default: on.

func (*Module) SetMockRules

func (m *Module) SetMockRules(rules []MockRule)

SetMockRules sets the read-only mock rules from buggregator.yaml. Invalid rules are logged and skipped.

func (*Module) Type

func (m *Module) Type() string

type OpenAPIImport

type OpenAPIImport struct {
	Spec    string `json:"spec"`    // the spec text (YAML or JSON)
	URL     string `json:"url"`     // or where to download it (http/https)
	Project string `json:"project"` // project of the rules; empty = every project
	Group   string `json:"group"`   // group name; default "openapi:<title>", "openapi:<project>:<title>" with a project
	// BasePath goes before every path; nil = the path of servers[0].url
	// ("/v1" from "https://api.example.com/v1"), "" = none.
	BasePath *string `json:"base_path"`
}

OpenAPIImport is what to import and how.

type OpenAPIResult

type OpenAPIResult struct {
	Group   string        `json:"group"`
	Title   string        `json:"title"`
	Rules   []MockRule    `json:"rules"`
	Skipped []OpenAPISkip `json:"skipped"`
}

OpenAPIResult is the outcome of an import.

func OpenAPIRulesFromFile

func OpenAPIRulesFromFile(path string, in OpenAPIImport) (OpenAPIResult, error)

OpenAPIRulesFromFile builds the rules of a spec file (for config rules: not stored, read-only once set with SetMockRules).

type OpenAPISkip

type OpenAPISkip struct {
	Method string `json:"method"`
	Path   string `json:"path"`
	Reason string `json:"reason"`
}

OpenAPISkip is an operation the import could not turn into a rule.

type ValidationError

type ValidationError map[string]string

ValidationError lists invalid fields of a rule: field → message.

func (ValidationError) Error

func (v ValidationError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL