gock

Versatile HTTP traffic mocking for Go, intercepting any net/http-based client for deterministic tests.

Library
Go
vv1.2.0
2,218stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
43/100Fair
Development Activity0
Maintenance20
Community52
Maturity60
Momentum40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
65/100Good
Architecture68
Code Quality70
Innovation55
Learning Curve65

gock is a Go library for mocking and intercepting HTTP traffic in tests, giving developers a fluent, expressive DSL to declare expected outgoing requests and their canned responses without touching application code. It hooks into the standard net/http transport layer, so it works transparently with any http.Client-based code, including third-party HTTP clients built on top of net/http.

Mocks are declared as ordered expectations that match on method, URL, headers, query parameters, path parameters, and request bodies (with JSON/XML helpers and regex support), and gock can fall back to real networking on a per-mock or per-suite basis. Because it operates at the http.RoundTripper level, it captures unmatched requests for inspection, supports response delays and simulated errors, and exposes hooks for custom matchers and request/response mappers, making it a practical dependency-free tool for writing deterministic HTTP integration tests.

What You Get

  • Fluent Request/Response DSL for declaring HTTP mocks (gock.New(...).Get(...).Reply(...))
  • Transparent interception of http.DefaultTransport and any custom http.Client/http.RoundTripper
  • Built-in JSON/XML body helpers, plus regex header, query, path-parameter, and body matching
  • Real-networking fallback with per-mock or global filters when nothing matches
  • Persistent and counted (Times) mocks, plus observability via gock.Observe and unmatched-request tracking

Common Use Cases

  • Unit-testing HTTP client code without hitting real third-party APIs
  • Simulating error responses, timeouts, and network delays to test resilience/retry logic
  • Verifying the exact shape (headers, query params, JSON bodies) of outgoing requests sent by an API client
  • Mocking a custom http.Client/http.RoundTripper used by libraries like gentleman
  • Debugging intercepted traffic during development via gock.Observe(gock.DumpRequest)

Under The Hood

Architecture gock centers on a package-level global mock registry (store.go’s mocks slice, guarded by storeMutex) that every gock.New(...) call feeds via Register. The interception point is a single Transport (transport.go) implementing http.RoundTripper, swapped into http.DefaultTransport by Intercept() or attached to an arbitrary http.Client via InterceptClient; its RoundTrip method is the funnel through which every outgoing request is checked against MatchMock (matcher.go), which walks the registered mocks in FIFO order and defers to a per-mock MockMatcher pipeline (method, scheme, host, path, headers, query/path params, body — matchers.go) before a matched Mock builds its response. Request/Response/Mock are small, focused structs wired together at creation time (NewMock) rather than through dependency injection, so the design reads as a deliberate, nock-inspired global-singleton pattern rather than a layered application; changing the shape of the global mocks store or the Transport swap mechanism would ripple through nearly every file, since almost all package state ultimately funnels through those two points.

Tech Stack Written in plain Go 1.13 with effectively zero runtime dependencies — go.mod lists only github.com/h2non/parth for RESTful path-parameter extraction and github.com/nbio/st as a lightweight test-assertion helper. There’s no web framework, ORM, or database involved since gock’s entire surface is net/http: it reimplements just enough of http.RoundTripper, http.Header, and JSON/XML (de)serialization (via the stdlib encoding/json/encoding/xml) to intercept and fabricate responses. Builds and tests run through plain go build/go test, with .travis.yml driving CI on Travis, and the package explicitly advertises itself as “dependency free” as a design goal.

Code Quality Each source file has a matching _test.go counterpart (nine pairs covering gock, matcher, matchers, mock, request, responder, response, store, and transport), using github.com/nbio/st’s st.Expect for assertions rather than the stdlib testing package’s raw comparisons. Error handling is explicit throughout — matcher functions consistently return (bool, error) instead of panicking or silently swallowing failures, and mutex-guarded state (the mock store, the disabler, the config singleton) is protected consistently across concurrent access paths. Naming follows idiomatic Go conventions with godoc-style comments on virtually every exported type and function, giving the package strong self-documentation; the main gaps are the absence of a modern linter/vet configuration and reliance on the (now largely superseded) Travis CI rather than GitHub Actions.

API Design The public API is a fluent, chainable DSL — gock.New(url).Get(path).MatchHeader(...).Reply(status).JSON(body) — that reads close to a sentence describing the expected HTTP exchange, directly mirroring the ergonomics of Node’s nock (credited in the README as its inspiration). Getting started requires no boilerplate beyond importing the package and calling gock.New; sensible defaults (a full built-in matcher stack, automatic Content-Type inference for .JSON()/.XML()) mean most test cases need only a few lines, while power users can still drop down to custom MatchFuncs, request/response mappers, and pluggable Matcher implementations for edge cases documented via the _examples/ directory’s twenty runnable scenarios.

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