### 5-Second Setup Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md A quick guide to setting up httpmock for tests: activate mocking, register responders, and make HTTP calls. Cleanup is handled automatically. ```go // 1. Activate mocking httpmock.Activate(t) // 2. Register responders httpmock.RegisterResponder(method, url, responder) // 3. Make HTTP calls in test resp, _ := http.Get(url) // Cleanup automatic when using Activate(t) ``` -------------------------------- ### tdsuite Example for HTTP Mocking Source: https://github.com/jarcoal/httpmock/blob/v1/README.md Integrates httpmock with tdsuite for testing HTTP requests. Activates mocking in Setup and resets it in PostTest. ```go // article_test.go import ( "testing" "github.com/jarcoal/httpmock" "github.com/maxatome/go-testdeep/helpers/tdsuite" "github.com/maxatome/go-testdeep/td" ) type MySuite struct{} func (s *MySuite) Setup(t *td.T) error { // block all HTTP requests httpmock.Activate(t) return nil } func (s *MySuite) PostTest(t *td.T, testName string) error { // remove any mocks after each test httpmock.Reset() return nil } func TestMySuite(t *testing.T) { tdsuite.Run(t, &MySuite{}) } func (s *MySuite) TestArticles(assert, require *td.T) { httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json", httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`)) // do stuff that makes a request to articles.json } ``` -------------------------------- ### Minimal Working Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Activate httpmock, register a responder for a specific GET request, and then make the HTTP call. Cleanup is automatic when using Activate(t). ```go import "github.com/jarcoal/httpmock" func TestAPI(t *testing.T) { httpmock.Activate(t) httpmock.RegisterResponder("GET", "https://api.example.com/users", httpmock.NewStringResponder(200, `[{"id":1}]`)) // Test code that calls http.Get(), http.Post(), etc. resp, _ := http.Get("https://api.example.com/users") // resp is mocked, returns 200 with your body } ``` -------------------------------- ### Example: Register No Responder Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/global-functions.md Example of registering a `NotFoundResponder` which will call `t.Fatal` with the URL and stack trace for any unmocked request. ```go httpmock.RegisterNoResponder(httpmock.NewNotFoundResponder(t.Fatal)) ``` -------------------------------- ### Basic HTTP Mocking Example Source: https://github.com/jarcoal/httpmock/blob/v1/README.md Activate httpmock for testing and register responders for specific HTTP methods and URLs. Use NewStringResponder for simple string responses. This example shows exact URL matching and regular expression matching. ```go func TestFetchArticles(t *testing.T) { httpmock.Activate(t) // Exact URL match httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles", httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`)) // Regexp match (could use httpmock.RegisterRegexpResponder instead) httpmock.RegisterResponder("GET", `=~^https://api\.mybiz\.com/articles/id/\d+\z`, httpmock.NewStringResponder(200, `{"id": 1, "name": "My Great Article"}`)) // do stuff that makes a request to articles ... // get count info httpmock.GetTotalCallCount() // get the amount of calls for the registered responder info := httpmock.GetCallCountInfo() info["GET https://api.mybiz.com/articles"] // number of GET calls made to https://api.mybiz.com/articles info["GET https://api.mybiz.com/articles/id/12"] // number of GET calls made to https://api.mybiz.com/articles/id/12 info[`GET =~^https://api\.mybiz\.com/articles/id/\d+\z`] // number of GET calls made to https://api.mybiz.com/articles/id/ } ``` -------------------------------- ### Start and Stop Mocking Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use `Activate()` to start mocking and `Deactivate()` or `DeactivateAndReset()` to stop. `Activate(t)` provides automatic cleanup with `defer httpmock.DeactivateAndReset()`. ```go httpmock.Activate() // Start mocking ``` ```go httpmock.Activate(t) // Start + auto-cleanup with Cleanup() ``` ```go httpmock.Deactivate() // Stop, keep responders ``` ```go httpmock.DeactivateAndReset() // Stop + clear responders ``` ```go httpmock.Reset() // Clear all responders ``` -------------------------------- ### Basic Body Matching Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Example demonstrating how to register a responder that only responds to requests with a specific body content. ```APIDOC ## Basic Body Matching ### Description Only respond to requests with specific body content. ### Code Example ```go // Only respond to requests with specific body content httpmock.RegisterMatcherResponder("POST", "/users", httpmock.BodyContainsString(`"admin":true`), httpmock.NewStringResponder(403, "Forbidden")) ``` ``` -------------------------------- ### Combined Matching Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Example demonstrating how to combine multiple matchers (header and body size) for a single request. ```APIDOC ## Combined Matching ### Description Match both header and body criteria. ### Code Example ```go // Match both header and body criteria contentJson := httpmock.HeaderIs("Content-Type", "application/json") bodySize := httpmock.NewMatcher("size-check", func(req *http.Request) bool { body, _ := io.ReadAll(req.Body) return len(body) > 100 }) combined := contentJson.And(bodySize) httpmock.RegisterMatcherResponder("POST", "/large", combined, httpmock.NewStringResponder(202, "Accepted")) ``` ``` -------------------------------- ### Ginkgo Example for HTTP Mocking Source: https://github.com/jarcoal/httpmock/blob/v1/README.md Demonstrates httpmock usage with Ginkgo. Activates mocks before all tests and resets them before each test. ```go // article_suite_test.go import ( // ... "github.com/jarcoal/httpmock" ) // ... var _ = BeforeSuite(func() { // block all HTTP requests httpmock.Activate() }) var _ = BeforeEach(func() { // remove any mocks httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) // article_test.go import ( // ... "github.com/jarcoal/httpmock" ) var _ = Describe("Articles", func() { It("returns a list of articles", func() { httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json", httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`)) // do stuff that makes a request to articles.json }) }) ``` -------------------------------- ### Header-Based Routing Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Example showing how to route responses based on the presence of a specific header. ```APIDOC ## Header-Based Routing ### Description Respond differently based on authentication. ### Code Example ```go // Respond differently based on authentication httpmock.RegisterMatcherResponder("GET", "/data", httpmock.HeaderExists("Authorization"), httpmock.NewStringResponder(200, "authenticated data")) httpmock.RegisterResponder("GET", "/data", httpmock.NewStringResponder(401, "Unauthorized")) ``` ``` -------------------------------- ### Custom Matcher Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use NewMatcher to create a custom matcher with a specific name and a function to evaluate the match. ```go NewMatcher("", fn) ``` -------------------------------- ### File Responder Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use File().String() to mock an HTTP response with content read from a file. ```go NewStringResponder(200, File("body.json").String()) ``` -------------------------------- ### Serve Static Files Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Examples of serving static files like CSS, JavaScript, and images using `httpmock.File()` with different responder types. ```go httpmock.RegisterResponder("GET", "/styles.css", httpmock.NewStringResponder(200, httpmock.File("styles.css").String())) httpmock.RegisterResponder("GET", "/app.js", httpmock.NewStringResponder(200, httpmock.File("app.js").String())) httpmock.RegisterResponder("GET", "/logo.png", httpmock.NewBytesResponder(200, httpmock.File("logo.png").Bytes())) ``` -------------------------------- ### Header Value Matcher Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use HeaderIs to create a matcher that checks if a specific header has a particular value. ```go HeaderIs("Content-Type", "application/json") ``` -------------------------------- ### Alternative Response Based on Header Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Example illustrating how to provide alternative responses based on header values, with a default fallback. ```APIDOC ## Alternative Response Based on Header ### Description First matcher: admin user Second matcher: non-admin user (no matcher = default) ### Code Example ```go // First matcher: admin user admin := httpmock.HeaderIs("X-Role", "admin") httpmock.RegisterMatcherResponder("DELETE", "/users/123", admin, httpmock.NewStringResponder(204, "")) // Second matcher: non-admin user (no matcher = default) httpmock.RegisterResponder("DELETE", "/users/123", httpmock.NewStringResponder(403, "Forbidden")) ``` ``` -------------------------------- ### Go Function Signature Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/INDEX.md Illustrates the standard Go function signature format used in documentation. This format clearly defines function name, parameters with their types, and the return type. ```go func Name(param1 Type1, param2 Type2) ReturnType ``` -------------------------------- ### Advanced HTTP Mocking with Custom Responders Source: https://github.com/jarcoal/httpmock/blob/v1/README.md Use custom responder functions for more complex scenarios, such as generating JSON responses dynamically or extracting data from requests. This example demonstrates mocking GET, POST, and conditional responses using body content matching. ```go func TestFetchArticles(t *testing.T) { httpmock.Activate(t) // our database of articles articles := make([]map[string]interface{}, 0) // mock to list out the articles httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles", func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(200, articles) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }) // return an article related to the request with the help of regexp submatch (\d+) httpmock.RegisterResponder("GET", `=~^https://api\.mybiz\.com/articles/id/(\d+)\z`, func(req *http.Request) (*http.Response, error) { // Get ID from request id := httpmock.MustGetSubmatchAsUint(req, 1) // 1=first regexp submatch return httpmock.NewJsonResponse(200, map[string]interface{}{ "id": id, "name": "My Great Article", }) }) // mock to add a new article httpmock.RegisterResponder("POST", "https://api.mybiz.com/articles", func(req *http.Request) (*http.Response, error) { article := make(map[string]interface{}) if err := json.NewDecoder(req.Body).Decode(&article); err != nil { return httpmock.NewStringResponse(400, ""), nil } articles = append(articles, article) resp, err := httpmock.NewJsonResponse(200, article) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }) // mock to add a specific article, send a Bad Request response // when the request body contains `"type":"toy"` httpmock.RegisterMatcherResponder("POST", "https://api.mybiz.com/articles", httpmock.BodyContainsString(`"type":"toy"`), httpmock.NewStringResponder(400, `{"reason":"Invalid article type"}`)) // do stuff that adds and checks articles } ``` -------------------------------- ### Header-Based Routing Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Demonstrates routing based on the presence of a specific header. If the 'Authorization' header exists, a specific response is returned; otherwise, a default unauthorized response is provided. ```go // Respond differently based on authentication httpmock.RegisterMatcherResponder("GET", "/data", httpmock.HeaderExists("Authorization"), httpmock.NewStringResponder(200, "authenticated data")) httpmock.RegisterResponder("GET", "/data", httpmock.NewStringResponder(401, "Unauthorized")) ``` -------------------------------- ### Initialize and Control Mocking Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/README.md Functions to start, stop, and reset the HTTP mocking functionality. ```APIDOC ## Initialize and Control Mocking ### Start mocking - `Activate()` - `ActivateNonDefault()` ### Stop mocking - `Deactivate()` - `DeactivateAndReset()` ### Clear responders - `Reset()` ### Clear counters - `ZeroCallCounters()` ``` -------------------------------- ### Create New MockTransport Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/configuration.md Creates a new MockTransport with default settings. Use this as a starting point for configuring your mock transport. ```go transport := httpmock.NewMockTransport() transport.DontCheckMethod = true // Disable method validation client := &http.Client{Transport: transport} ``` -------------------------------- ### Header Exists Matcher Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use HeaderExists to create a matcher that checks if a specific header is present in the request. ```go HeaderExists("Authorization") ``` -------------------------------- ### Import httpmock Package Source: https://github.com/jarcoal/httpmock/blob/v1/README.md Import the httpmock package into your Go files to start using its mocking capabilities. This is typically done at the beginning of your test files. ```go import "github.com/jarcoal/httpmock" ``` -------------------------------- ### Error Responder Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use NewErrorResponder to mock an HTTP response that results in an error. ```go NewErrorResponder(err) ``` -------------------------------- ### Ginkgo + Resty Example for HTTP Mocking Source: https://github.com/jarcoal/httpmock/blob/v1/README.md Shows httpmock integration with Ginkgo and Resty. Activates non-default transport for Resty's client and registers JSON responders. ```go // article_suite_test.go import ( // ... "github.com/jarcoal/httpmock" "github.com/go-resty/resty/v2" ) // ... // global client (using resty.New() creates a new transport each time, // so you need to use the same one here and when making the request) var client = resty.New() var _ = BeforeSuite(func() { // block all HTTP requests httpmock.ActivateNonDefault(client.GetClient()) }) var _ = BeforeEach(func() { // remove any mocks httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) // article_test.go import ( // ... "github.com/jarcoal/httpmock" ) type Article struct { Status struct { Message string `json:"message"` Code int `json:"code"` } `json:"status"` } var _ = Describe("Articles", func() { It("returns a list of articles", func() { fixture := `{"status":{"message": "Your message", "code": 200}}` // have to use NewJsonResponder to get an application/json content-type // alternatively, create a go object instead of using json.RawMessage responder, _ := httpmock.NewJsonResponder(200, json.RawMessage(`{"status":{"message": "Your message", "code": 200}}`) fakeUrl := "https://api.mybiz.com/articles.json" httpmock.RegisterResponder("GET", fakeUrl, responder) // fetch the article into struct articleObject := &Article{} _, err := resty.R().SetResult(articleObject).Get(fakeUrl) // do stuff with the article object ... }) }) ``` -------------------------------- ### String Responder Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use NewStringResponder to mock an HTTP response with a given status code and string body. ```go NewStringResponder(200, "OK") ``` -------------------------------- ### Registering String Responder with File Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Loads an HTML file and registers it as a string response for a GET request. ```APIDOC ## GET /page ### Description Loads an HTML file and serves its content as a string response. ### Method GET ### Endpoint /page ### Request Body None ### Response #### Success Response (200) - **Content-Type**: text/plain; charset=utf-8 - **Body**: Contents of the page.html file. ### Request Example ```go httpmock.RegisterResponder("GET", "/page", httpmock.NewStringResponder(200, httpmock.File("page.html").String())) ``` ``` -------------------------------- ### Documentation Conventions Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/MANIFEST.txt Details the conventions used for documenting types, parameters, return values, and code examples. ```APIDOC ## Conventions Used ### Type Signatures: `func Name(param Type) ReturnType` `func Name(p1 T1, p2 T2) (R1, R2, error)` ### Parameter Documentation: Markdown tables with columns: | Parameter | Type | Required | Default | Description | ### Return Documentation: - Single return: described directly - Multiple returns: listed individually - Errors: always documented separately ### Code Examples: - Real usage patterns (not test code) - Realistic and complete - Often follow "Example:" heading - Show both correct and common-mistake patterns ### Source References: `github.com/jarcoal/httpmock/filename.go` (lines X-Y) ### Related Links: Cross-references using "Related:" section Links to other documentation Links to related functions/types ``` -------------------------------- ### Registering XML Responder with File Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Loads an XML file and registers it as an XML response for a GET request. ```APIDOC ## GET /feed ### Description Loads an XML file and serves its content as an XML response. ### Method GET ### Endpoint /feed ### Request Body None ### Response #### Success Response (200) - **Content-Type**: application/xml - **Body**: Contents of the feed.xml file. ### Request Example ```go httpmock.RegisterResponder("GET", "/feed", httpmock.NewXmlResponder(200, httpmock.File("feed.xml"))) ``` ``` -------------------------------- ### Quick Lookup Guides Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/MANIFEST.txt Provides quick access to API functionality through indexes organized by purpose and use case. ```APIDOC ## Quick Lookup Guides ### By Purpose (in README.md): - Initialize and control mocking - Register responders - Create responses - Add matching criteria - Modify responders (chaining) - Track calls - Extract submatch data - Load from files ### By Use Case (in INDEX.md): - Mock a simple GET request - Respond based on headers/body - Respond with dynamic URL data - Catch unmocked routes - Test retry/backoff - Simulate slow endpoints - Debug "no responder found" - Disable mocking ``` -------------------------------- ### Load File with Panic Recovery Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md The File.String() and File.Bytes() methods panic on error. Use `recover` in a `defer` function if you need to handle these panics during test setup. ```go // File.String() and File.Bytes() panic on error // Use recover if needed in test setup defer func() { if r := recover(); r != nil { t.Fatalf("Failed to load test data: %v", r) } }() body := httpmock.File("missing.json").String() // Will panic if not found ``` -------------------------------- ### Basic Body Matching Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Register a responder that only matches requests with specific body content. This is useful for testing endpoints that require exact payload matches. ```go // Only respond to requests with specific body content httpmock.RegisterMatcherResponder("POST", "/users", httpmock.BodyContainsString(`"admin":true`), httpmock.NewStringResponder(403, "Forbidden")) ``` -------------------------------- ### MustGetSubmatchAsInt Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/submatch-extraction.md Use MustGetSubmatchAsInt to extract a captured substring and convert it to an int64. This function panics if the submatch is not found or if the conversion fails. ```go httpmock.RegisterResponder("GET", `=~^/articles/(\d+)$`, func(req *http.Request) (*http.Response, error) { id := httpmock.MustGetSubmatchAsInt(req, 1) return httpmock.NewJsonResponseOrPanic(200, map[string]any{ "id": id, }), nil }) ``` -------------------------------- ### Bytes Responder Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use NewBytesResponder to mock an HTTP response with a given status code and byte slice body. ```go NewBytesResponder(200, []byte{}) ``` -------------------------------- ### JSON Responder Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use NewJsonResponder to mock an HTTP response with a given status code and JSON data. ```go NewJsonResponder(200, data) ``` -------------------------------- ### MustGetSubmatchAsUint Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/submatch-extraction.md Use MustGetSubmatchAsUint to extract a captured substring and convert it to a uint64. This function panics if the submatch is not found or if the conversion fails. ```go httpmock.RegisterResponder("DELETE", `=~^/items/(\d+)$`, func(req *http.Request) (*http.Response, error) { id := httpmock.MustGetSubmatchAsUint(req, 1) // Delete item with id return httpmock.NewStringResponder(204,விற்கு)(req) }) ``` -------------------------------- ### Create and Configure MockTransport Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/mock-transport.md Creates a new MockTransport instance and registers a basic string responder for a specific GET request. This is useful for setting up mock responses for simple API endpoints. ```Go transport := httpmock.NewMockTransport() client := &http.Client{Transport: transport} transport.RegisterResponder("GET", "http://example.com/api", httpmock.NewStringResponder(200, "OK")) resp, _ := client.Get("http://example.com/api") ``` -------------------------------- ### MustGetSubmatchAsFloat Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/submatch-extraction.md Use MustGetSubmatchAsFloat to extract a captured substring and convert it to a float64. This function panics if the submatch is not found or if the conversion fails. ```go httpmock.RegisterResponder("PATCH", `=~^/prices/(\d+)=(\d+\.\d+)$`, func(req *http.Request) (*http.Response, error) { price := httpmock.MustGetSubmatchAsFloat(req, 2) return httpmock.NewJsonResponseOrPanic(200, map[string]any{ "price": price, }), nil }) ``` -------------------------------- ### Registering JSON Responder with File Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Loads a JSON file, marshals its content, and registers it as a JSON response for a GET request. ```APIDOC ## GET /api/data ### Description Loads a JSON file, marshals its content, and serves it as a JSON response. ### Method GET ### Endpoint /api/data ### Request Body None ### Response #### Success Response (200) - **Content-Type**: application/json - **Body**: Marshaled content of the data.json file. ### Request Example ```go httpmock.RegisterResponder("GET", "/api/data", httpmock.NewJsonResponder(200, httpmock.File("data.json"))) ``` ``` -------------------------------- ### Example: Reset Between Tests Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/global-functions.md Demonstrates using `httpmock.Reset()` within `t.Run` to clear mocks and call counters before each sub-test, ensuring test isolation. ```go func TestMultipleTests(t *testing.T) { httpmock.Activate() defer httpmock.Deactivate() t.Run("TestA", func(t *testing.T) { httpmock.RegisterResponder("GET", "/test-a", ...) // test code httpmock.Reset() // Clear for next test }) t.Run("TestB", func(t *testing.T) { httpmock.RegisterResponder("GET", "/test-b", ...) // test code }) } ``` -------------------------------- ### Registering Bytes Responder with File Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Loads a binary file (e.g., PDF, image) and registers it as a byte array response for a GET request. ```APIDOC ## GET /report.pdf ### Description Loads a binary file and serves its content as a byte array response. ### Method GET ### Endpoint /report.pdf ### Request Body None ### Response #### Success Response (200) - **Body**: Contents of the report.pdf file as raw bytes. ### Request Example ```go httpmock.RegisterResponder("GET", "/report.pdf", httpmock.NewBytesResponder(200, httpmock.File("report.pdf").Bytes())) ``` ``` -------------------------------- ### MustGetSubmatch Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/submatch-extraction.md Use MustGetSubmatch to extract a captured substring from a request URL. This function panics if the submatch is not found or if the index is invalid (less than 1). ```go httpmock.RegisterResponder("GET", `=~^/users/([^/]+)$`, func(req *http.Request) (*http.Response, error) { username := httpmock.MustGetSubmatch(req, 1) return httpmock.NewJsonResponseOrPanic(200, map[string]any{ "username": username, }), nil }) ``` -------------------------------- ### Alternative Response Based on Header Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Shows how to provide different responses based on a header value. An 'admin' role gets a successful deletion response, while other roles receive a forbidden response. ```go // First matcher: admin user admin := httpmock.HeaderIs("X-Role", "admin") httpmock.RegisterMatcherResponder("DELETE", "/users/123", admin, httpmock.NewStringResponder(204, "")) // Second matcher: non-admin user (no matcher = default) httpmock.RegisterResponder("DELETE", "/users/123", httpmock.NewStringResponder(403, "Forbidden")) ``` -------------------------------- ### Example: Zero Call Counters Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/global-functions.md Shows how `ZeroCallCounters()` resets the total call count to 0 while keeping the registered responder active. This is useful for verifying call counts after specific operations. ```go httpmock.Activate() httpmock.RegisterResponder("GET", "/api", httpmock.NewStringResponder(200, "OK")) resp, _ := http.Get("/api") // Increases counter count := httpmock.GetTotalCallCount() // Returns 1 httpmock.ZeroCallCounters() count = httpmock.GetTotalCallCount() // Returns 0, responder still registered ``` -------------------------------- ### Manage Multiple HTTP Clients Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Activate mocking for the default client or a custom client using `ActivateNonDefault()`. Remember to `defer DeactivateNonDefault()` for custom clients. ```go // Default client httpmock.Activate(t) ``` ```go // Custom client client := &http.Client{Timeout: 10 * time.Second} httpmock.ActivateNonDefault(client) defer httpmock.DeactivateNonDefault(client) httpmock.RegisterResponder(...) // Register responder for the custom client resp, _ := client.Get(url) // Uses mock ``` -------------------------------- ### How to Use This Reference Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/MANIFEST.txt Guidance on navigating and utilizing the httpmock documentation based on user needs. ```APIDOC ## How to Use This Reference First Time Using httpmock? → Read `00-START-HERE.txt`, then `QUICK-REFERENCE.md` Looking for specific documentation? → Use `INDEX.md` "By Use Case" section Want API reference? → Use `README.md` "Quick API Index by Purpose" Need comprehensive understanding? → Start with `README.md`, then read relevant sections in order Troubleshooting? → Check `errors.md` for common scenarios Want to know all options? → Check `configuration.md` Need to understand request matching? → See `README.md` "Request Matching Algorithm" ``` -------------------------------- ### Get Matcher Name Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Retrieves the name of a matcher. Auto-generated names include details about their origin. ```go matcher := httpmock.BodyContainsString("test") name := matcher.Name() // Auto-generated name like "~0000000001@main.TestFunc() file.go:42" ``` -------------------------------- ### Get Number of Responders Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/mock-transport.md Returns the count of currently registered responders, excluding the no-responder fallback. ```go transport.NumResponders() ``` -------------------------------- ### Organize Test Data with Fixtures Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Demonstrates a common pattern for organizing test data using a `fixtures` directory. This approach helps keep test responses separate and manageable. ```go func TestAPI(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "/api/data", httpmock.NewJsonResponder(200, httpmock.File("fixtures/api_response_200.json"))) httpmock.RegisterResponder("GET", "/api/missing", httpmock.NewJsonResponder(404, httpmock.File("fixtures/api_response_404.json"))) // ... test code ... } ``` -------------------------------- ### Register XML Responder with File Content Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Use httpmock.File("feed.xml") to load XML content from a file and serve it. ```go // Load XML from file httpmock.RegisterResponder("GET", "/feed", httpmock.NewXmlResponder(200, httpmock.File("feed.xml"))) ``` -------------------------------- ### Multiple Clients Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Demonstrates how to use httpmock with the default HTTP client and custom HTTP clients. ```APIDOC ## Multiple Clients ### Default Client Activate mocking for the default `http.Client`: ```go httpmock.Activate(t) ``` ### Custom Client Activate mocking for a specific `http.Client` instance: ```go client := &http.Client{Timeout: 10 * time.Second} httpmock.ActivateNonDefault(client) defer httpmock.DeactivateNonDefault(client) httpmock.RegisterResponder(...) // Register responders for the custom client resp, _ := client.Get(url) // This request will use the mock ``` ``` -------------------------------- ### Configure Responder with Method Chaining Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/configuration.md Configure a responder by chaining methods to set status, body, headers, and simulate latency. Use this to define the mock response behavior. ```go responder := httpmock.NewStringResponder(200, "data") .SetContentLength() // Auto-set Content-Length header .HeaderSet(http.Header{ "X-Custom": []string{"value"}, }) // Replace headers .Delay(100 * time.Millisecond) // Simulate latency .Times(5, t.Log) // Callable 5 times max .Trace(t.Logf) // Log each call httpmock.RegisterResponder("GET", "/api", responder) ``` -------------------------------- ### Registering Multiple Responders from Files Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Shows how to register multiple responders, each loading data from a different file for different endpoints. ```APIDOC ## Multiple Responders from Files This example demonstrates registering several responders, each serving content from a distinct file. ```go httpmock.RegisterResponder("GET", "/users", httpmock.NewJsonResponder(200, httpmock.File("users.json"))) httpmock.RegisterResponder("GET", "/posts", httpmock.NewJsonResponder(200, httpmock.File("posts.json"))) httpmock.RegisterResponder("POST", "/upload", httpmock.NewBytesResponder(200, httpmock.File("response.dat").Bytes())) ``` ``` -------------------------------- ### Register String Responder with File Content Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Use httpmock.File("page.html").String() to load HTML content from a file and serve it. ```go // Load HTML from file httpmock.RegisterResponder("GET", "/page", httpmock.NewStringResponder(200, httpmock.File("page.html").String())) ``` -------------------------------- ### Using File with ResponderFromMultipleResponses Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Demonstrates how to use files to define multiple sequential responses within a single responder. ```APIDOC ## In ResponderFromMultipleResponses This example shows how to use files to define a sequence of responses for a single endpoint. ```go httpmock.RegisterResponder("GET", "/stream", httpmock.ResponderFromMultipleResponses([]*http.Response{ httpmock.NewJsonResponseOrPanic(202, httpmock.File("processing.json")), httpmock.NewJsonResponseOrPanic(200, httpmock.File("complete.json")), })) ``` ``` -------------------------------- ### Get Total Call Count Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/mock-transport.md Returns the total number of HTTP calls intercepted since activation or last reset. ```go transport.GetTotalCallCount() ``` -------------------------------- ### Multiple Responders from Files Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Register multiple responders that serve content from different files for various endpoints and methods. ```go httpmock.RegisterResponder("GET", "/users", httpmock.NewJsonResponder(200, httpmock.File("users.json"))) httpmock.RegisterResponder("GET", "/posts", httpmock.NewJsonResponder(200, httpmock.File("posts.json"))) httpmock.RegisterResponder("POST", "/upload", httpmock.NewBytesResponder(200, httpmock.File("response.dat").Bytes())) ``` -------------------------------- ### Body Contains String Matcher Example Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Use BodyContainsString to create a matcher that checks if the request body contains a specific string. ```go BodyContainsString("admin") ``` -------------------------------- ### Load from Files Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/README.md Utilities for creating responders or response bodies from file paths. ```APIDOC ## Load from Files ### Create file reference - `File("path")` ### As string - `File("path").String()` ### As bytes - `File("path").Bytes()` ``` -------------------------------- ### Create Responder from HTTP Response Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Wraps a manually constructed http.Response into a Responder. ```go func ResponderFromResponse(resp *http.Response) Responder ``` -------------------------------- ### Create String Responder Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Use this function to create a responder with a string body. ```go func NewStringResponder(status int, body string) Responder ``` -------------------------------- ### String Method for File Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Retrieves the file contents as a string. Panics if file reading fails. Implements fmt.Stringer. ```go func (f File) String() string ``` ```go body := httpmock.File("response.json").String() httpmock.RegisterResponder("GET", "/data", httpmock.NewStringResponder(200, body)) ``` -------------------------------- ### Control Flow Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Manage the lifecycle of the httpmock server. Activate it to start mocking and deactivate to stop. Reset clears responders without deactivating. ```APIDOC ## Control Flow ### Start Mocking - `httpmock.Activate()`: Starts the mocking server. - `httpmock.Activate(t)`: Starts the mocking server with automatic cleanup using `t.Cleanup()`. ### Stop Mocking - `httpmock.Deactivate()`: Stops the mocking server, keeping registered responders. - `httpmock.DeactivateAndReset()`: Stops the mocking server and clears all registered responders. ### Reset Mocking (Keep Active) - `httpmock.Reset()`: Clears all registered responders while keeping the mocking server active. ``` -------------------------------- ### Create XML Responder Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Creates a responder with an XML-marshaled body and sets the Content-Type header to application/xml. Returns an error if marshaling fails. ```go func NewXmlResponder(status int, body any) (Responder, error) ``` -------------------------------- ### Verify Calls Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Provides methods to inspect the call counts of registered mocks, including getting all call information, the total number of calls, and resetting counters. ```APIDOC ## Verify Calls ```go // Get all calls info := httpmock.GetCallCountInfo() // info["GET https://api.example.com/users"] == 2 // Get total calls count := httpmock.GetTotalCallCount() // Reset counters httpmock.ZeroCallCounters() ``` ``` -------------------------------- ### Create Custom Matcher Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Use NewMatcher to create a custom matcher with a name and a MatcherFunc. The MatcherFunc receives an *http.Request and returns true if the request matches. ```go matcher := httpmock.NewMatcher("admin-check", func(req *http.Request) bool { return req.Header.Get("X-Admin") == "true" }) ``` -------------------------------- ### Create XML Responder or Panic Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Similar to NewXmlResponder, but panics if the XML marshaling fails instead of returning an error. ```go func NewXmlResponderOrPanic(status int, body any) Responder ``` -------------------------------- ### Register Bytes Responder with File Content Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Use httpmock.File("report.pdf").Bytes() to load binary file content (like images or PDFs) and serve it. ```go // Load binary file (image, PDF, etc.) httpmock.RegisterResponder("GET", "/report.pdf", httpmock.NewBytesResponder(200, httpmock.File("report.pdf").Bytes())) ``` -------------------------------- ### Register Responder with Query Options Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/configuration.md Register a responder with query parameter matching. Supports url.Values, map[string]string, or a raw query string. Matching is order-independent. ```go // Option 1: url.Values import "net/url" query := url.Values{ "page": []string{"1"}, "limit": []string{"10"}, } httpmock.RegisterResponderWithQuery("GET", "/search", query, responder) ``` ```go // Option 2: map[string]string query := map[string]string{ "page": "1", "limit": "10", } httpmock.RegisterResponderWithQuery("GET", "/search", query, responder) ``` ```go // Option 3: Query string httpmock.RegisterResponderWithQuery("GET", "/search", "page=1&limit=10", responder) ``` -------------------------------- ### List Registered Responders Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/mock-transport.md Returns a list of registered responder descriptors as strings in the format "METHOD URL" or "METHOD URL ", sorted alphabetically. ```go transport.Responders() ``` -------------------------------- ### Get Call Count Information Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/mock-transport.md Returns a map of all calls matched, keyed as "METHOD URL" with counts as values. Regexp responders generate 2 entries per call (matched URL and the pattern). ```go info := transport.GetCallCountInfo() count := info["GET https://api.example.com/users"] ``` -------------------------------- ### Get Call Count Info - Go Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/global-functions.md Retrieves a map of all intercepted calls, keyed by "METHOD URL", with call counts as values. Regexp responders generate 2 entries per call (actual URL and pattern). ```go func GetCallCountInfo() map[string]int ``` ```go httpmock.RegisterResponder("GET", "https://api.example.com/users", httpmock.NewStringResponder(200, "users")) http.Get("https://api.example.com/users") http.Get("https://api.example.com/users") info := httpmock.GetCallCountInfo() // info["GET https://api.example.com/users"] == 2 ``` -------------------------------- ### Combined Header and Body Matching Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Illustrates combining multiple matchers (header and custom body size check) using the And method. This allows for complex request matching criteria. ```go // Match both header and body criteria contentJson := httpmock.HeaderIs("Content-Type", "application/json") bodySize := httpmock.NewMatcher("size-check", func(req *http.Request) bool { body, _ := io.ReadAll(req.Body) return len(body) > 100 }) combined := contentJson.And(bodySize) httpmock.RegisterMatcherResponder("POST", "/large", combined, httpmock.NewStringResponder(202, "Accepted")) ``` -------------------------------- ### Log Responder Calls with Trace Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/responder.md Utilize `.Trace(fn func(...any))` to log every invocation of a responder using a provided callback function, which is helpful for debugging test execution flow. ```go httpmock.RegisterResponder("GET", "/api", httpmock.NewStringResponder(200, "OK").Trace(t.Log)) ``` -------------------------------- ### Printing File Content vs. Filename Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Demonstrates how to print the content of a file using File.String() and its filename by casting the File object to a string. ```go file := httpmock.File("data.txt") // Print content (uses File.String()) fmt.Printf("File content: %v\n", file) // Output: File content: // Print filename (cast to string first) fmt.Printf("Filename: %s\n", string(file)) // Output: Filename: data.txt ``` -------------------------------- ### Responders Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/mock-transport.md Returns a list of strings, where each string describes a registered responder. The format is "METHOD URL" or "METHOD URL ". The list is sorted alphabetically. ```APIDOC ## Responders ### Description Returns a list of registered responder descriptors as strings in format "METHOD URL" or "METHOD URL ", sorted alphabetically. ### Method Signature ```go func (m *MockTransport) Responders() []string ``` ### Returns - `[]string` - List of responder descriptions. ``` -------------------------------- ### MatcherFunc.And Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/matcher.md Combines multiple MatcherFunc instances using AND logic. ```APIDOC ## MatcherFunc.And ### Description Combines matcher functions with AND logic. ### Signature ```go func (mf MatcherFunc) And(mfs ...MatcherFunc) MatcherFunc ``` ### Returns - `MatcherFunc` - Combined AND function. ``` -------------------------------- ### Create JSON Responder Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Creates a responder with a JSON-marshaled body and sets the Content-Type header to application/json. Returns an error if marshaling fails. ```go func NewJsonResponder(status int, body any) (Responder, error) ``` -------------------------------- ### Version Information Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/MANIFEST.txt Provides essential version and import path details for the httpmock library. ```APIDOC ## Version Information Package: `github.com/jarcoal/httpmock` Branch: `v1` (use v1 branch or specify in go.mod) Go Versions Supported: `1.16` to `1.26+` Import Path: `github.com/jarcoal/httpmock` Repository: `https://github.com/jarcoal/httpmock` Package Docs: `https://pkg.go.dev/github.com/jarcoal/httpmock` ``` -------------------------------- ### Responder Chaining Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Illustrates how to chain multiple responder options together to customize behavior such as call count limits, fallback responders, latency, headers, and logging. ```APIDOC ## Responder Chaining ```go httpmock.NewStringResponder(200, "data") .Times(3) // Callable 3 times max .Then(fallback) // Use fallback on 4th call .Delay(100*time.Millisecond) // Add latency .HeaderSet(header) // Set response headers .SetContentLength() // Auto-set Content-Length .Trace(t.Log) // Log each call ``` ``` -------------------------------- ### Create Responder from Multiple HTTP Responses Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Creates a responder that returns different http.Responses on successive calls. An optional function can be provided for custom logic. ```go func ResponderFromMultipleResponses(responses []*http.Response, fn ...func(...any)) Responder ``` -------------------------------- ### Handle ErrSubmatchNotFound Error Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/submatch-extraction.md Demonstrates how to check if an error returned by `GetSubmatch*` is `ErrSubmatchNotFound`. ```go id, err := httpmock.GetSubmatchAsInt(req, 5) if errors.Is(err, httpmock.ErrSubmatchNotFound) { // Submatch 5 doesn't exist } ``` -------------------------------- ### ResponderFromMultipleResponses with Files Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Use ResponderFromMultipleResponses to chain responses from files, suitable for simulating streams or sequences of events. ```go httpmock.RegisterResponder("GET", "/stream", httpmock.ResponderFromMultipleResponses([]*http.Response{ httpmock.NewJsonResponseOrPanic(202, httpmock.File("processing.json")), httpmock.NewJsonResponseOrPanic(200, httpmock.File("complete.json")), })) ``` -------------------------------- ### Register Responder with Regexp and Matcher Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/global-functions.md Combines regular expression URL matching with additional matcher criteria. This provides a powerful way to define complex matching rules for requests. ```go httpmock.RegisterRegexpMatcherResponder("GET", rx, matcher, responder) ``` -------------------------------- ### Register Responders Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/QUICK-REFERENCE.md Demonstrates various ways to register responders for different URL matching strategies, including exact URLs, path-only matching, regular expressions, and URL-encoded query parameters. ```APIDOC ## Register Patterns ```go // Exact URL httpmock.RegisterResponder("GET", "https://api.com/users", responder) // Path only httpmock.RegisterResponder("GET", "/users", responder) // Regexp httpmock.RegisterRegexpResponder("GET", regexp.MustCompile(`/users/\d+`), responder) // URL with "=~" prefix (equivalent to regexp) httpmock.RegisterResponder("GET", "=~^/users/\d+$", responder) // With query params (order-independent) httpmock.RegisterResponderWithQuery("GET", "/search", map[string]string{"q": "golang"}, responder) // With matcher httpmock.RegisterMatcherResponder("POST", "/users", httpmock.BodyContainsString("admin"), responder) // Fallback for unmocked routes httpmock.RegisterNoResponder(httpmock.NewNotFoundResponder(t.Fatal)) ``` ``` -------------------------------- ### Create HeaderExists Matcher Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Creates a matcher that verifies the presence of a specific header key in the request. Use this when the existence of a header is important, regardless of its value. ```go func HeaderExists(key string) Matcher ``` -------------------------------- ### Create Bytes Responder Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Use this function to create a responder with a byte slice body. ```go func NewBytesResponder(status int, body []byte) Responder ``` -------------------------------- ### Create JSON HTTP Response or Panic Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Similar to NewJsonResponse, but panics if the JSON marshaling fails instead of returning an error. ```go func NewJsonResponseOrPanic(status int, body any) *http.Response ``` -------------------------------- ### Bytes Method for File Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/file-helper.md Retrieves the file contents as a byte slice. Panics if file reading fails. ```go func (f File) Bytes() []byte ``` ```go body := httpmock.File("image.png").Bytes() httpmock.RegisterResponder("GET", "/image", httpmock.NewBytesResponder(200, body)) ``` -------------------------------- ### MustGetSubmatchAsUint Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/api-reference/submatch-extraction.md Retrieves a captured submatch and attempts to convert it to a uint64. Panics on error. ```APIDOC ## MustGetSubmatchAsUint ### Description Retrieves a captured submatch from a request URI and attempts to convert it into a `uint64`. This function is a panic-on-error variant of `GetSubmatchAsUint`, suitable when you are certain the submatch exists and is a valid unsigned integer. ### Signature ```go func MustGetSubmatchAsUint(req *http.Request, n int) uint64 ``` ### Parameters #### Path Parameters - **req** (*http.Request) - Required - The HTTP request object from which to extract the submatch. - **n** (int) - Required - The 1-based index of the submatch to retrieve and convert. ### Returns - **uint64** - The captured substring converted to a `uint64`. ### Panics - If the submatch at the given index `n` is not found. - If the captured submatch cannot be parsed as a `uint64`. - If `n` is less than 1. ### Example ```go httpmock.RegisterResponder("DELETE", `=~^/items/(\d+)$`, func(req *http.Request) (*http.Response, error) { id := httpmock.MustGetSubmatchAsUint(req, 1) // Delete item with id return httpmock.NewStringResponder(204, "")(req) }) ``` ``` -------------------------------- ### Create XML HTTP Response Source: https://github.com/jarcoal/httpmock/blob/v1/_autodocs/types.md Creates an http.Response with an XML-marshaled body. Returns an error if marshaling fails. ```go func NewXmlResponse(status int, body any) (*http.Response, error) ```