### Install govcr Go Module (Latest Version) Source: https://github.com/seborama/govcr/blob/master/README.md This command installs the latest stable version of the govcr Go module using `go get`. It fetches the module and its dependencies, making it available for use in Go projects. ```bash go get github.com/seborama/govcr/v17@latest ``` -------------------------------- ### Simple VCR Usage Example in Go Source: https://github.com/seborama/govcr/blob/master/README.md This example demonstrates the basic usage of govcr to record and replay HTTP requests. The first execution makes a live HTTP call and saves it to a cassette file. Subsequent executions replay the call from the cassette, avoiding live network interaction. It uses a 'relaxed' request matcher to handle varying HTTP headers like 'Age' that might otherwise prevent a match. ```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") } ``` -------------------------------- ### Install Legacy govcr Go Module (v4) Source: https://github.com/seborama/govcr/blob/master/README.md This command installs a specific legacy version (v4) of the govcr Go module, suitable for projects not using Go Modules. It uses `go get` to fetch the older version. ```bash go get gopkg.in/seborama/govcr.v4 ``` -------------------------------- ### Go: Examples of `On` Conditions for Track Mutators Source: https://github.com/seborama/govcr/blob/master/README.md Illustrates how to combine `Any`, `All`, and `Not` functions with `On` conditions for `govcr` track mutators. These predicates define the logical criteria that must be met for a mutator to be applied, enabling complex conditional logic. ```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). ``` -------------------------------- ### Decrypting govcr Cassette Files via CLI Source: https://github.com/seborama/govcr/blob/master/README.md This recipe demonstrates how to decrypt existing govcr cassette files using the provided command-line utility. It covers the installation of the `govcr` CLI tool and provides an example of how to use the `decrypt` command with specified cassette and key files. The utility writes the decrypted content to standard output for safety. ```bash go install github.com/seborama/govcr/v17/cmd/govcr@latest ``` ```bash govcr decrypt -cassette-file my.cassette.json -key-file my.key ``` -------------------------------- ### Run Project Tests Source: https://github.com/seborama/govcr/blob/master/README.md Execute the test suite for the `govcr` project. For S3-specific tests, ensure LocalStack is installed and configured, or provide valid AWS credentials. ```bash make test ``` -------------------------------- ### Changing govcr Cassette Encryption Cipher Source: https://github.com/seborama/govcr/blob/master/README.md This Go recipe illustrates how to change the encryption cipher of a govcr cassette using the `SetCipher` method. It shows an example of setting a new cipher with `encryption.NewChaCha20Poly1305WithRandomNonceGenerator` and a secret key. Note that this method is for changing ciphers, not for removing encryption. ```go vcr := govcr.NewVCR(...) err := vcr.SetCipher( encryption.NewChaCha20Poly1305WithRandomNonceGenerator, "my_secret.key", ) ``` -------------------------------- ### Integrate govcr with Custom Go HTTP Client Source: https://github.com/seborama/govcr/blob/master/README.md This recipe demonstrates how to configure `govcr` to work with an application's custom `http.Client` instance, which might have specific `http.Transport` settings like TLS configurations or timeouts. `govcr` wraps the provided client, allowing tests to use `vcr.HTTPClient()` while preserving the original client's transport. ```Go // See TestExample2 in tests for fully working example. func TestExample2() { // Create a custom http.Transport for our app. tr := http.DefaultTransport.(*http.Transport) tr.TLSClientConfig = &tls.Config{ InsecureSkipVerify: true, // just an example, not recommended } // Create an instance of myApp. // It uses the custom Transport created above and a custom Timeout. app := &myApp{ httpClient: &http.Client{ Transport: tr, Timeout: 15 * time.Second, }, } // Instantiate VCR. vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName2), govcr.WithClient(app.httpClient), ) // Inject VCR's http.Client wrapper. // The original transport has been preserved, only just wrapped into VCR's. app.httpClient = vcr.HTTPClient() // Run request and display stats. app.Get("https://example.com/foo") } ``` -------------------------------- ### VCRSettings Configuration Options Source: https://github.com/seborama/govcr/blob/master/README.md The `VCRSettings` structure allows detailed configuration of the govcr recorder. Settings are applied using `With*` options, enabling customization of the underlying HTTP client, request matching, and track mutation behaviors. ```APIDOC VCRSettings: Purpose: Contains parameters for configuring the govcr recorder. Configuration Methods (With* options): WithClient: Description: Provides a custom http.Client. Type: *http.Client Default: Go's default http.Client WithRequestMatchers: Description: Defines custom request matching logic. Type: []RequestMatcher WithTrackRecordingMutators: Description: Modifies tracks before recording. Type: []TrackMutator WithTrackReplayingMutators: Description: Modifies tracks before replaying. Type: []TrackMutator WithLogging: Description: Enables internal logging for debugging. Type: boolean Default: disabled ``` -------------------------------- ### Encrypt govcr Cassettes with a Key Source: https://github.com/seborama/govcr/blob/master/README.md This recipe demonstrates how to enable encryption for `govcr` cassettes using a specified cipher and a key file. This enhances the security of recorded HTTP interactions by encrypting the cassette content, protecting sensitive data from unauthorized access. ```Go // See TestExample4 in tests for fully working example. vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName4). WithCipher( encryption.NewChaCha20Poly1305WithRandomNonceGenerator, "test-fixtures/TestExample4.unsafe.key"), ) ``` -------------------------------- ### Configure govcr for Normal HTTP Playback Mode Source: https://github.com/seborama/govcr/blob/master/README.md This recipe illustrates how to set `govcr` to its default 'Normal HTTP mode'. In this mode, `govcr` attempts to replay from the cassette if a matching track is found; otherwise, it makes a live HTTP call. No special options are required as this is the default behavior. ```Go vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName2), // Normal mode is default, no special option required :) ) // or equally: vcr.SetNormalMode() ``` -------------------------------- ### Configuring govcr with AWS S3 Cassette Storage Source: https://github.com/seborama/govcr/blob/master/README.md This Go recipe demonstrates how to configure govcr to store cassettes on AWS S3. It shows how to initialize an S3 client and then integrate it with `govcr.NewVCR` using `fileio.NewAWS` and `WithStore`. This allows for persistent cassette storage in an S3 bucket. ```go // See TestExample5 in tests for fully working example. s3Client := /* ... */ s3f := fileio.NewAWS(s3Client) vcr := govcr.NewVCR(govcr. NewCassetteLoader(exampleCassetteName5). WithStore(s3f), ) ``` -------------------------------- ### Implementing a Custom Request Matcher in govcr Source: https://github.com/seborama/govcr/blob/master/README.md This Go recipe explains how to create a custom `RequestMatcher` to ignore specific request headers, such as `X-Custom-Timestamp`, during the matching process. This is crucial when header values are unpredictable or change per request, ensuring that the VCR can correctly replay recorded tracks by modifying the request inputs for comparison without affecting the originals. ```go vcr.SetRequestMatchers( govcr.DefaultMethodMatcher, govcr.DefaultURLMatcher, func(httpRequest, trackRequest *track.Request) bool { // we can safely mutate our inputs: // mutations affect other RequestMatcher's but _not_ the // original HTTP request or the cassette Tracks. httpRequest.Header.Del("X-Custom-Timestamp") trackRequest.Header.Del("X-Custom-Timestamp") return govcr.DefaultHeaderMatcher(httpRequest, trackRequest) }, ) ``` -------------------------------- ### Configure govcr for Live-Only HTTP Mode Source: https://github.com/seborama/govcr/blob/master/README.md This recipe shows how to configure `govcr` to operate in 'Live only' mode. In this mode, `govcr` will never replay from the cassette and will always make live HTTP calls, effectively bypassing cassette playback entirely. This is useful for ensuring tests always hit the actual service. ```Go vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName2), govcr.WithLiveOnlyMode(), ) // or equally: vcr.SetLiveOnlyMode() ``` -------------------------------- ### Import govcr Go Module Source: https://github.com/seborama/govcr/blob/master/README.md This Go import statement makes the govcr package available within a Go source file. It allows the program to use the VCR functionalities provided by the library. ```go import "github.com/seborama/govcr/v17" ``` -------------------------------- ### RequestMatcher Functionality Source: https://github.com/seborama/govcr/blob/master/README.md govcr uses `RequestMatcher` functions to compare incoming HTTP requests against recorded tracks on a cassette. Default matchers provide strict or relaxed comparisons, and custom matchers can be implemented to handle dynamic request elements like timestamps or identifiers. ```APIDOC RequestMatcher: Purpose: Compares an incoming HTTP request to a recorded track. Input Parameters: Scoped to the RequestMatchers; do not affect the original HTTP request or cassette tracks. Default Behaviors: Strict: Comparison Criteria: Request headers, method, full URL, body, and trailers. Relaxed (NewMethodURLRequestMatcher): Comparison Criteria: Method and full URL only. Customization: Ability to create custom matchers to ignore or modify specific request parts (e.g., timestamps, dynamic identifiers). ``` -------------------------------- ### Using a Replaying Track Mutator in govcr Source: https://github.com/seborama/govcr/blob/master/README.md This Go recipe demonstrates how to use a replaying `Track Mutator` to handle dynamic headers like `X-Transaction-Id` that change per request. It involves configuring a custom request matcher to ignore the header during comparison and then using `track.ResponseDeleteHeaderKeys` and `track.ResponseTransferHTTPHeaderKeys` to inject the correct value from the current HTTP request into the replayed response, ensuring consistency. ```go // See TestExample3 in tests for fully working example. vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName3), govcr.WithRequestMatchers( func(httpRequest, trackRequest *track.Request) bool { // Remove the header from comparison. // Note: this removal is only scoped to the request matcher, it does not affect the original HTTP request httpRequest.Header.Del("X-Transaction-Id") trackRequest.Header.Del("X-Transaction-Id") return govcr.DefaultHeaderMatcher(httpRequest, trackRequest) }, ), govcr.WithTrackReplayingMutators( // Note: although we deleted the headers in the request matcher, this was limited to the scope of // the request matcher. The replaying mutator's scope is past request matching. track.ResponseDeleteHeaderKeys("X-Transaction-Id"), // do not append to existing values track.ResponseTransferHTTPHeaderKeys("X-Transaction-Id"), ), ) ``` -------------------------------- ### Encrypt govcr Cassettes with Custom Nonce Generator Source: https://github.com/seborama/govcr/blob/master/README.md This recipe extends cassette encryption by showing how to provide a custom nonce generator. This allows for more control over the cryptographic nonce generation process, which can be important for specific security requirements or integration with existing cryptographic infrastructure. ```Go type myNonceGenerator struct{} func (ng myNonceGenerator) Generate() ([]byte, error) { nonce := make([]byte, 12) if _, err := io.ReadFull(rand.Reader, nonce); err != nil { return nil, err } return nonce, nil } vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName4). WithCipherCustomNonce( encryption.NewChaCha20Poly1305, "test-fixtures/TestExample4.unsafe.key", nonceGenerator), ) ``` -------------------------------- ### Configure govcr for Offline HTTP Mode Source: https://github.com/seborama/govcr/blob/master/README.md This recipe explains how to configure `govcr` to operate in 'Offline' mode. In this mode, `govcr` will only playback from the cassette and will return a transport error if no matching track is found. This is ideal for ensuring tests are fully isolated from external network dependencies. ```Go vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName2), govcr.WithOfflineMode(), ) // or equally: vcr.SetOfflineMode() ``` -------------------------------- ### Configure govcr for Read-Only Cassette Mode Source: https://github.com/seborama/govcr/blob/master/README.md This recipe demonstrates how to set `govcr` to 'Read only' cassette mode. In this mode, `govcr` behaves normally by replaying from the cassette or making live calls, but it disables any recording to the cassette. This is useful for preventing accidental modifications to existing cassettes. ```Go vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName2), govcr.WithReadOnlyMode(), ) // or equally: vcr.SetReadOnlyMode(true) // `false` to disable option ``` -------------------------------- ### Remove Response TLS during govcr Playback Source: https://github.com/seborama/govcr/blob/master/README.md This recipe demonstrates how to apply the `track.ResponseDeleteTLS` mutator during cassette playback. This ensures that the `Response.TLS` field is removed from tracks when they are replayed, which can be useful for testing scenarios where TLS details are irrelevant or problematic. ```Go vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName2), govcr.WithTrackReplayingMutators(track.ResponseDeleteTLS()), // ^^^^^^^^^ ) // or, similarly: vcr.AddReplayingMutators(track.ResponseDeleteTLS()) // ^^^^^^^^^ ``` -------------------------------- ### Remove Response TLS during govcr Recording Source: https://github.com/seborama/govcr/blob/master/README.md This recipe shows how to use the `track.ResponseDeleteTLS` mutator to remove the `Response.TLS` field from a cassette during the recording phase. This is useful for ensuring sensitive TLS information is not stored in the cassette or for making recordings more consistent across different environments. ```Go vcr := govcr.NewVCR( govcr.NewCassetteLoader(exampleCassetteName2), govcr.WithTrackRecordingMutators(track.ResponseDeleteTLS()), // ^^^^^^^^^ ) // or, similarly: vcr.AddRecordingMutators(track.ResponseDeleteTLS()) // ^^^^^^^^^ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.