Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

govcr

> 测试质量
Open source

HTTP mock for Golang: record and replay HTTP/HTTPS interactions for offline testing

200 stars0 likes0 views
WebsiteGitHub

About

HTTP mock for Golang: record and replay HTTP/HTTPS interactions for offline testing

govcr

⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
⭐️
⭐️ Community Support Appeal
⭐️
⭐️ Please show your love by giving a star to this project.
⭐️
⭐️ It takes a lot of personal time and effort to maintain and expand features.
⭐️
⭐️ If you are using govcr, show me it is worth my continuous effort by giving it a star.
⭐️
⭐️ **You'll be my star **
⭐️
⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️

Records and replays HTTP / HTTPS interactions for offline unit / behavioural / integration tests thereby acting as an HTTP mock. You can also use goovcr for API simulation.

This project was inspired by php-vcr which is a PHP port of VCR for ruby.

This project is an adaptation for Google's Go / Golang programming language.

Table of content

  • govcr
    • Table of content
    • Simple VCR example
    • Install
    • Glossary of Terms
    • Concepts
      • VCRSettings
    • Match a request to a cassette track
    • Track mutators
    • Cassette encryption
    • Cookbook
      • Run the examples
      • Recipe: VCR with custom http.Client
      • Recipe: Remove Response TLS
      • Recipe: Change the playback mode of the VCR
        • Normal HTTP mode
        • Live only HTTP mode
        • Read only cassette mode
        • Offline HTTP mode
      • Recipe: VCR with encrypted cassette
      • Recipe: VCR with encrypted cassette - custom nonce generator
      • Recipe: Cassette decryption
      • Recipe: Changing cassette encryption
      • Recipe: VCR with cassette storage on AWS S3
      • Recipe: VCR with a custom RequestMatcher
      • Recipe: VCR with a replaying Track Mutator
      • Recipe: VCR with a recording Track Mutator
      • More
    • Stats
    • Run the tests
    • Bugs
    • Improvements
    • Limitations
      • Go empty interfaces (interface{} / any)
      • Support for multiple values in HTTP headers
      • HTTP transport errors
    • Contribute
    • Community Support Appeal

Simple VCR example

go
// See TestExample1 in tests for fully working example.
func TestExample1() {
    vcr := govcr.NewVCR(
        govcr.NewCassetteLoader("MyCassette1.json"),
        govcr.WithRequestMatchers(govcr.NewMethodURLRequestMatchers()...), // use a "relaxed" request matcher
    )

    vcr.Client.Get("http://example.com/foo")
}

The first time you run this example, MyCassette1.json won't exist and TestExample1 will make a live HTTP call.

On subsequent executions (unless you delete the cassette file), the HTTP call will be played back from the cassette and no live HTTP call will occur.

Note:

We use a "relaxed" request matcher because example.com injects an "Age" header that varies per-request. Without a mutator, govcr's default strict matcher would not match the track on the cassette and keep sending live requests (and record them to the cassette).

(toc)

Install

bash
go get github.com/seborama/govcr/v17@latest

For all available releases, please check the releases tab on github.

And your source code would use this import:

go
import "github.com/seborama/govcr/v17"

For versions of govcr before v5 (which don't use go.mod), use a dependency manager to lock the version you wish to use (perhaps v4)!

bash
# download legacy version of govcr (without go.mod)
go get gopkg.in/seborama/govcr.v4

(toc)

Glossary of Terms

VCR: Video Cassette Recorder. In this context, a VCR refers to the engine and data that this project provides. A VCR is both an HTTP recorder and player. When you use a VCR, HTTP requests are replayed from previous recordings (tracks saved in cassette files, on the filesystem or in AWS S3, etc). When no previous recording exists for the request, it is performed live on the HTTP server, after what it is saved to a track on the cassette.

cassette: a sequential collection of tracks. This is in effect a JSON file.

Long Play cassette: a cassette compressed in gzip format. Such cassettes have a name that ends with '.gz'.

tracks: a record of an HTTP request. It contains the request data, the response data, if available, or the error that occurred.

ControlPanel: the creation of a VCR instantiates a ControlPanel for interacting with the VCR and conceal its internals.

(toc)

Concepts

govcr is a wrapper around the Go http.Client. It can record live HTTP traffic to files (called "cassettes") and later replay HTTP requests ("tracks") from them instead of live HTTP calls.

Cassette files can be stored on the filesystem or on a cloud storage service (AWS S3), etc.

The code documentation can be found on godoc.

When using govcr's http.Client, the request is matched against the tracks on the 'cassette':

  • The track is played where a matching one exists on the cassette,
  • otherwise the request is executed live to the HTTP server and then recorded on cassette for the next time.

Note on a govcr typical flow

The normal govcr flow is test-oriented. Traffic is recorded by default unless a track already existed on the cassette at the time it was loaded.

A typical usage:

  • run your test once to produce the cassette
  • from this point forward, when the test runs again, it will use the cassette

During live recording, the same request can be repeated and recorded many times. Playback occurs in the order the requests were saved on the cassette. See the tests for an example (TestConcurrencySafety).

(toc)

VCRSettings

This structure contains parameters for configuring your govcr recorder.

Settings are populated via With* options:

  • Use WithClient to provide a custom http.Client otherwise the default Go http.Client will be used.
  • See vcrsettings.go for more options such as WithRequestMatchers, WithTrackRecordingMutators, WithTrackReplayingMutators, ...
  • TODO: WithLogging enables logging to help understand what govcr is doing internally.

(toc)

Match a request to a cassette track

By default, govcr uses a strict RequestMatcher function that compares the request's headers, method, full URL, body, and trailers.

Another RequestMatcher (obtained with NewMethodURLRequestMatcher) provides a more relaxed comparison based on just the method and the full URL.

In some scenarios, it may not possible to match tracks exactly as they were recorded.

This may be the case when the request contains a timestamp or a dynamically changing identifier, etc.

You can create your own matcher on any part of the request and in any manner (like ignoring or modifying some headers, etc).

The input parameters received by a RequestMatcher are scoped to the RequestMatchers. This affects the other RequestMatcher's. But it does not permeate throughout the VCR to the original incoming HTTP request or the tracks read from or written to the cassette.

(toc)

Track mutators

The live HTTP request and response traffic is protected against modifications. While govcr could easily support in-place mutation of the live traffic, this is not a goal.

Nonetheless, govcr supports mutating tracks, either at recording time or at playback time.

In either case, this is achieved with track Mutators.

A Mutator can be combined with one or more On conditions. All On conditions attached to a mutator must be true for the mutator to apply - in other words, they are logically "and-ed".

To help construct more complex yet readable predicates easily, govcr provides these pre-defined functions for use with On:

  • Any achieves a logical "or" of the provided predicates.
  • All achieves a logical "and" of the provided predicates.
  • Not achieves a logical "not" of the provided predicates.
  • None is synonymous of "Not Any".

Examples:

go
myMutator.
    On(Any(...)). // proceeds if any of the "`...`" predicates is true
    On(Not(Any(...)))  // proceeds if none of the "`...`" predicates is true (i.e. all predicates are false)
    On(Not(All(...))).  // proceeds if not every (including none) of the "`...`" predicates is true (i.e. at least one predicate is false, possibly all of them).

A track recording mutator can change both the request and the response that will be persisted to the cassette.

A track replaying mutator transforms the track after it was matched and retrieved from the cassette. It does not change the cassette file.

While a track replaying mutator could change the request, it serves no purpose since the request has already been made and matched to a track by the time the replaying mutator is invoked. The reason for supplying the request in the replaying mutator is for information. In some situations, the request details are needed to transform the response.

The track replaying mutator additionally receives an informational copy of the current HTTP request in the track's Response under the Request field i.e. Track.Response.Request. This is useful for tailoring track replays with current request information. See TestExample3 for illustration.

Refer to the tests for examples (search for WithTrackRecordingMutators and WithTrackReplayingMutators).

(toc)

Cassette encryption

Your cassettes are likely to contain sensitive information in practice. You can choose to not persist it to the cassette with a recording track mutator. However, in some situations, this information is needed. Enters cassette encryption.

Cassettes can be encrypted with two Go-supported ciphers:

  • AES-GCM (12-byte nonce, 16 or 32-byte key)
  • ChaCha20Poly1305 (24-byte nonce, 32-byte key)

You will need to provide a secret key to a "Crypter" that will take care of encrypting to file and decrypting from file the cassette contents transparently.

The cryptographic "nonce" is stored with the cassette, in its header. The default strategy to generate a n-byte random nonce.

It is possible to provide a custom nonce generator.

Cassettes are expected to be of somewhat reasonable size (at the very most a few MiB). They are fully loaded in memory. Under these circumstances, chunking is not needed and not supported.

As a reminder, you should never use a nonce value more than once with the same private key. It would compromise the encryption.

Please refer to the Cookbook for decryption and changes to encryption (such as cipher & key rotation).

(toc)

Cookbook

Run the examples

Please refer to the examples directory for examples of code and uses.

**Observe the output of the examples between the 1st run and the 2nd run

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Goapi-simulationaws-s3gogo-vcr

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category测试质量
PricingOpen source

> Related tools

J
Jest
JavaScript 测试框架
P
Playwright
现代端到端测试框架
E
eslint-plugin-test-selectors
Enforces that data-test-id attributes are added to interactive DOM elements (JSX) to help with UI testing. JSX only.