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,079 stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum. How we score it →
63 /100 Good
Development Activity 60
Maintenance 36
Community 56
Maturity 60
Momentum 40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation. How we score it →
78 /100 Good
Architecture 82
Code Quality 90
Innovation 75
Learning Curve 65

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
88%
Apache 2.0

Apache Airflow

Data Engineering

47,133

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
64
Dependency
Built with
Python 88%
Updated today
Go
72%
Other

Convoy

Developer Tools · Devops

2,877

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
87
Repo Health
81
Technical
66
Dependency
Built with
Go 72%
TypeScript 15%
HTML 12%
Updated 1 weeks ago
Go
91%
Apache 2.0

Ory Kratos

Authentication

13,913

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

View details
79
Repo Health
78
Technical
65
Dependency
Built with
Go 91%
Updated 2 months ago
Rust
47%
MIT

Svix

Automation · Developer Tools

3,441

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
91
Repo Health
77
Technical
67
Dependency
Built with
Rust 47%
C# 16%
Updated yesterday
Go
90%
BSD 3

tau

Devops

5,176

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
79
Repo Health
82
Technical
64
Dependency
Built with
Go 90%
Updated 1 months 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