用于 Golang 的 HTTP 模拟: 记录和重放 HTTP/HTTPS 交互以进行离线测试
⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
⭐️
⭐️ 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.
http.Client// 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).
go get github.com/seborama/govcr/v17@latestFor all available releases, please check the releases tab on github.
And your source code would use this import:
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)!
# download legacy version of govcr (without go.mod)
go get gopkg.in/seborama/govcr.v4VCR: 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.
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':
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:
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).
This structure contains parameters for configuring your govcr recorder.
Settings are populated via With* options:
WithClient to provide a custom http.Client otherwise the default Go http.Client will be used.vcrsettings.go for more options such as WithRequestMatchers, WithTrackRecordingMutators, WithTrackReplayingMutators, ...WithLogging enables logging to help understand what govcr is doing internally.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.
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:
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).
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:
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).
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,或尚未同步最近议题。