httpmock

Drop-in HTTP mocking for Go that intercepts requests at the http.RoundTripper level, so tests never touch the real network.

Library
Go
vv1.4.2
2,077stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
63/100Good
Development Activity64
Maintenance36
Community52
Maturity60
Momentum40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
78/100Good
Architecture82
Code Quality90
Innovation75
Learning Curve65

httpmock is a Go library for mocking HTTP responses in tests. It works by swapping out the Transport field of http.DefaultClient (or any custom *http.Client) with a MockTransport that intercepts outgoing requests and routes them to registered responders instead of hitting the network. Responders can be registered against an exact URL, a regexp pattern (prefixed with ”=~”), or a Matcher that inspects headers and body content, giving fine-grained control over which mock fires for a given request.

Beyond simple stubbing, httpmock tracks per-route call counts, supports chained responders via Then(), can extract regexp submatches from the request path, and ships JSON/XML/string/file/error response builders so tests rarely need to hand-roll an *http.Response. A dedicated race_test.go and CI matrix running go test -race across eleven Go versions plus tip signal that concurrent-safety of the shared transport state is treated as a first-class concern, not an afterthought.

What You Get

  • MockTransport implementing http.RoundTripper, swapped in via Activate()/ActivateNonDefault() for the default or a custom *http.Client
  • RegisterResponder / RegisterRegexpResponder / RegisterMatcherResponder for exact-URL, regexp, and header-or-body-aware mocking
  • A layered URL-matching fallback (exact URL, sorted query params, path-only, then regexp) so responders can be as loose or as strict as needed
  • Built-in response constructors: NewStringResponder, NewJsonResponder, NewXmlResponder, NewBytesResponder, NewErrorResponder, and file-backed responders
  • Per-route and total call-count tracking via GetCallCountInfo() / GetTotalCallCount(), useful for asserting a mock was actually hit
  • A NewNotFoundResponder helper plus “did you mean” suggestions when a request doesn’t match any registered route (e.g. wrong HTTP method casing)

Common Use Cases

  • Unit-testing code that calls a third-party HTTP API without making real network requests or standing up a fake server
  • Asserting exact request counts and bodies sent to an external API during a test, via GetCallCountInfo and body matchers
  • Simulating specific failure modes (timeouts, 500s, malformed JSON) from a dependency to test application error handling
  • Running test suites (via Ginkgo, tdsuite, or plain testing.T) where Activate(t) auto-resets mocks between tests using t.Cleanup

Under The Hood

Architecture The package centers on MockTransport, an http.RoundTripper implementation that replaces http.DefaultClient’s Transport (or a custom client’s, via ActivateNonDefault) so every outgoing request is intercepted before it reaches the network. RoundTrip in transport.go drives a layered lookup: findResponders walks a chain of key-generation strategies (exact URL, sorted query params, path-only, then their regexp counterparts) via the findForKey slice, stopping at the first registered match, and falls through to a suggestResponder helper that detects likely user mistakes like wrong HTTP-method casing or a trailing slash. Responder registration (RegisterResponder, RegisterMatcherResponder, RegisterRegexpResponder in match.go), response construction (response.go), file-backed fixtures (file.go), and shared low-level types (route keys, submatch extraction, stack-trace-aware errors) live in a separate internal/ subpackage, keeping the public API surface small while the supporting machinery stays encapsulated. Concurrency is handled with a sync.RWMutex guarding all responder maps and counters, and a dedicated race_test.go exercises this under Go’s race detector.

Tech Stack The library targets Go 1.16 through the latest toolchain and has a minimal dependency footprint: github.com/maxatome/go-testdeep is used only for assertions in the test suite, with davecgh/go-spew pulled in transitively. Production code depends solely on the Go standard library (net/http, regexp, sync, encoding/json, encoding/xml), which keeps it lightweight to vendor into any Go project. CI (.github/workflows/ci.yml) runs the full matrix across eleven Go versions plus tip, and a dedicated full-tests job runs golangci-lint (v2.13.1) and reports coverage to Coveralls.

Code Quality Test coverage is extensive and proportionate to the implementation: transport_test.go (1247 lines) and response_test.go (825 lines) roughly match or exceed the size of the files they cover, and match_test.go (500 lines) exercises matcher composition and ordering rules. A separate race_test.go specifically targets concurrent-safety, and CI runs go test -race on every push. Every exported function carries a doc comment written in Go’s linkable [Identifier] style, cross-referencing related APIs, and doc.go holds a dedicated package-level overview. Error handling favors typed, wrapped errors (internal.StackTracer, ErrorNoResponderFoundMistake) that carry call-site stack traces rather than opaque strings, and golangci-lint enforces style in CI (non-blocking on non-tip Go versions, blocking on the full-tests job).

What Makes It Unique Rather than the common approach of standing up a local httptest.Server, httpmock intercepts at the http.RoundTripper boundary, so it mocks arbitrary outbound calls without requiring the code under test to be pointed at a different base URL. Its URL-matching algorithm is unusually thorough: it tries the exact URL, then a canonicalized (sorted-query-param) version, then progressively strips query and host components before falling back to regexp responders, so a single registered mock can satisfy multiple equivalent request shapes. The matcher system (RegisterMatcherResponder) layers header/body-aware predicates on top of the URL match with a documented priority order (named matchers before the anonymous zero-matcher), and the suggestResponder heuristic that flags likely method-case or trailing-slash mistakes is a small but distinctive developer-experience touch not commonly found in comparable mocking libraries.

Used by 5 apps in this directory

Python
90%
Apache 2.0

Apache Airflow

Data Engineering

46,645

Define, schedule, and monitor complex data workflows as Python code — with a powerful UI, 80+ provider integrations, and battle-tested scalability across thousands of production deployments.

View details
96
Repo Health
89
Technical
65
Dependency
Built with
Python90%
Updated today
Go
73%
Other

Convoy

Developer Tools · Devops

2,862

Convoy is an open-source, cloud-native webhooks gateway that ingests events over HTTP or straight from Kafka, SQS, Google Pub/Sub, and RabbitMQ, then reliably delivers them to subscriber endpoints with signed payloads, automatic retries, circuit breaking, and JavaScript-based transformations.

View details
89
Repo Health
81
Technical
66
Dependency
Built with
Go73%
TypeScript13%
HTML12%
Updated yesterday
Go
91%
Apache 2.0

Ory Kratos

Authentication

13,853

API-first identity and user management that handles login, registration, MFA, and recovery so your application never has to.

View details
84
Repo Health
78
Technical
67
Dependency
Built with
Go91%
Updated 1 months ago
Rust
49%
MIT

Svix

Developer Tools · Automation

3,376

Open source, self-hostable webhook infrastructure that handles delivery, retries, HMAC signing, and multi-tenant event management so you never have to build a webhooks system from scratch.

View details
90
Repo Health
77
Technical
67
Dependency
Built with
Rust49%
C#15%
Updated 2 days ago
Go
90%
BSD 3

tau

Devops

5,133

Open-source, Git-native platform-as-a-service for building, deploying, and scaling fullstack apps on your own infrastructure with no DevOps required.

View details
83
Repo Health
82
Technical
65
Dependency
Built with
Go90%
Updated 2 weeks ago

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search