### Simple HTTP Mocking Example Source: https://pkg.go.dev/github.com/jarcoal/httpmock Demonstrates basic mocking of GET requests with exact and regular expression URL matching. Shows how to retrieve call counts for registered responders. ```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/ } ``` -------------------------------- ### go-testdeep + tdsuite Example Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use httpmock with go-testdeep's tdsuite for mocking HTTP requests in tests. Activate httpmock in Setup and reset 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 } ``` -------------------------------- ### ActivateNonDefault Source: https://pkg.go.dev/github.com/jarcoal/httpmock Starts the mock environment with a non-default http.Client, overriding its Transport field with DefaultTransport. ```APIDOC ## ActivateNonDefault ### Description Starts the mock environment with a non-default *http.Client. This emulates the Activate function, but allows for custom clients that do not use http.DefaultTransport directly. To do so, it overrides the client Transport field with DefaultTransport. ### Function Signature ```go func ActivateNonDefault(client *http.Client) ``` ### Usage Example ```go transport := http.DefaultTransport.(*http.Transport).Clone() transport.TLSHandshakeTimeout = 60 * time.Second client := &http.Client{Transport: transport} httpmock.ActivateNonDefault(client) ``` ### See Also See also DeactivateNonDefault, Deactivate and DeactivateAndReset. ``` -------------------------------- ### Ginkgo Example Source: https://pkg.go.dev/github.com/jarcoal/httpmock Integrate httpmock with Ginkgo for HTTP request mocking. Activate httpmock in BeforeSuite, reset in BeforeEach, and deactivate in AfterSuite. ```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 }) }) ``` -------------------------------- ### Activate Mock Environment for Test Source: https://pkg.go.dev/github.com/jarcoal/httpmock Activate starts the mock environment by replacing http.DefaultClient.Transport with DefaultTransport. Call this before your tests. It can optionally take a testing.TB to automatically manage cleanup. ```go func TestFetchArticles(t *testing.T) { httpmock.Activate(t) // all http requests using http.DefaultTransport will now be intercepted } ``` ```go httpmock.Activate() t.Cleanup(httpmock.DeactivateAndReset) ``` ```go func init() { httpmock.Activate() } ``` ```go func TestMain(m *testing.M) { httpmock.Activate() os.Exit(m.Run()) } ``` -------------------------------- ### Ginkgo + Resty Example Source: https://pkg.go.dev/github.com/jarcoal/httpmock Combine Ginkgo, Resty, and httpmock for testing HTTP clients. Use ActivateNonDefault with Resty's client and ensure consistent client usage. ```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 ... }) }) ``` -------------------------------- ### Activate Source: https://pkg.go.dev/github.com/jarcoal/httpmock Starts the mock environment, replacing the default http.Client.Transport with DefaultTransport. It can optionally take a testing.TB to automatically call DeactivateAndReset at the end of the test. ```APIDOC ## Activate ### Description Starts the mock environment. This should be called before your tests run. Under the hood this replaces the http.Client.Transport field of http.DefaultClient with DefaultTransport. ### Function Signature ```go func Activate(t ...testing.TB) ``` ### Usage Example ```go func TestFetchArticles(t *testing.T) { httpmock.Activate(t) // all http requests using http.DefaultTransport will now be intercepted } ``` ### Optional `testing.TB` Parameter When `t` is present, it allows to automatically call `DeactivateAndReset` at the end of the test. It is strictly equivalent to: ```go httpmock.Activate() t.Cleanup(httpmock.DeactivateAndReset) ``` ### Global Activation If you want all of your tests in a package to be mocked, just call Activate from init(): ```go func init() { httpmock.Activate() } ``` or using a TestMain function: ```go func TestMain(m *testing.M) { httpmock.Activate() os.Exit(m.Run()) } ``` ``` -------------------------------- ### Activate Mock Environment with Custom Client Source: https://pkg.go.dev/github.com/jarcoal/httpmock ActivateNonDefault starts the mock environment for a specific http.Client instance, overriding its Transport field with DefaultTransport. This is useful for clients not using http.DefaultTransport directly. ```go transport := http.DefaultTransport.(*http.Transport).Clone() transport.TLSHandshakeTimeout = 60 * time.Second client := &http.Client{Transport: transport} ``` ```go httpmock.ActivateNonDefault(client) ``` -------------------------------- ### Get Registered Responders Source: https://pkg.go.dev/github.com/jarcoal/httpmock Returns a list of currently registered responders as strings. Non-regexp responders are sorted alphabetically, followed by regexp responders in registration order. ```go func (m *MockTransport) Responders() []string ``` -------------------------------- ### Get File Content as String Source: https://pkg.go.dev/github.com/jarcoal/httpmock The String() method of the File type returns the file's content as a string, implementing fmt.Stringer. This is useful for creating string responses, such as with NewStringResponse or NewStringResponder. It panics if file opening or reading fails. ```go httpmock.NewStringResponder(200, httpmock.File("body.txt").String()) ``` -------------------------------- ### Get Submatch from Request Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a regexp from an http.Request. Must be used with RegisterRegexpResponder or RegisterResponder with a "=~" prefix. Panics if n < 1. ```go func GetSubmatch(req *http.Request, n int) (string, error) ``` ```go RegisterResponder("GET", `=~^/item/name/([^/]+)\z`, func(req *http.Request) (*http.Response, error) { name, err := GetSubmatch(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": 123, "name": name, }) }) ``` -------------------------------- ### Get Submatch as Uint from Request Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a regexp from an http.Request as a uint64. Must be used with RegisterRegexpResponder or RegisterResponder with a "=~" prefix. Panics if n < 1. ```go func GetSubmatchAsUint(req *http.Request, n int) (uint64, error) ``` ```go RegisterResponder("GET", `=~^/item/id/(\d+)\z`, func(req *http.Request) (*http.Response, error) { id, err := GetSubmatchAsUint(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": id, "name": "The beautiful name", }) }) ``` -------------------------------- ### Trace Responder Calls Source: https://pkg.go.dev/github.com/jarcoal/httpmock Returns a new Responder that allows tracing calls to the original Responder using a provided function (fn). This is particularly useful with the testing package, for example, using *testing.T.Log to log each time the Responder is invoked. This helps in debugging and understanding the flow of requests. ```go func (r Responder) Trace(fn func(...any)) Responder ``` ```go import ( "testing" "github.com/jarcoal/httpmock" ) ... func TestMyApp(t *testing.T) { ... httpmock.RegisterResponder("GET", "/foo/bar", httpmock.NewStringResponder(200, "{}").Trace(t.Log), ) ``` -------------------------------- ### Get File Content as Bytes Source: https://pkg.go.dev/github.com/jarcoal/httpmock The Bytes() method of the File type returns the file's content as a byte slice ([]byte). This is useful for creating byte-based responses, such as with NewBytesResponse or NewBytesResponder. It panics if file opening or reading fails. ```go httpmock.NewBytesResponder(200, httpmock.File("body.raw").Bytes()) ``` -------------------------------- ### Get Submatch as Int from Request Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a regexp from an http.Request as an int64. Must be used with RegisterRegexpResponder or RegisterResponder with a "=~" prefix. Panics if n < 1. ```go func GetSubmatchAsInt(req *http.Request, n int) (int64, error) ``` ```go RegisterResponder("GET", `=~^/item/id/(\d+)\z`, func(req *http.Request) (*http.Response, error) { id, err := GetSubmatchAsInt(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": id, "name": "The beautiful name", }) }) ``` -------------------------------- ### Get Submatch as Float from Request Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a regexp from an http.Request as a float64. Must be used with RegisterRegexpResponder or RegisterResponder with a "=~" prefix. Panics if n < 1. ```go func GetSubmatchAsFloat(req *http.Request, n int) (float64, error) ``` ```go RegisterResponder("PATCH", `=~^/item/id/\d+\?height=(\d+(?:\.\d*)?)\z`, func(req *http.Request) (*http.Response, error) { height, err := GetSubmatchAsFloat(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": id, "name": "The beautiful name", "height": height, }) }) ``` -------------------------------- ### Get Call Count Info Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves a map of all caught HTTP calls since activation or reset. Keys are method, space, and URL. Regexp responders generate two entries per call. ```go func GetCallCountInfo() map[string]int ``` ```go RegisterResponder("GET", `=~z\.com\z`, NewStringResponder(200, "body")) http.Get("http://z.com") ``` ```go map[string]int{ `GET http://z.com`: 1, `GET =~z\.com\z`: 1, } ``` -------------------------------- ### MockTransport.RegisterMatcherResponder Source: https://pkg.go.dev/github.com/jarcoal/httpmock RegisterMatcherResponder adds a new responder, associated with a given HTTP method, URL (or path) and Matcher. When a request comes in that matches, the responder is called and the response returned to the client. If url contains query parameters, their order matters as well as their content. If url begins with "=~", the following chars are considered as a regular expression. If this regexp can not be compiled, it panics. Note that the "=~" prefix remains in statistics returned by MockTransport.GetCallCountInfo. As 2 regexps can match the same URL, the regexp responders are tested in the order they are registered. Registering an already existing regexp responder (same method & same regexp string) replaces its responder, but does not change its position. Registering an already existing responder resets the corresponding statistics as returned by MockTransport.GetCallCountInfo. Registering a nil Responder removes the existing one and the corresponding statistics as returned by MockTransport.GetCallCountInfo. It does nothing if it does not already exist. The original matcher can be passed but also a new Matcher with the same name and a nil match function. See MockTransport.RegisterRegexpMatcherResponder to directly pass a *regexp.Regexp. If several responders are registered for a same method and url couple, but with different matchers, they are ordered depending on the following rules: the zero matcher, Matcher{} (or responder set using MockTransport.RegisterResponder) is always called lastly; other matchers are ordered by their name. If a matcher does not have an explicit name (NewMatcher called with an empty name and Matcher.WithName method not called), a name is automatically computed so all anonymous matchers are sorted by their creation order. An automatically computed name has always the form "~HEXANUMBER@PKG.FUNC() FILE:LINE". See NewMatcher for details. If method is a lower-cased version of CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT or TRACE, a panics occurs to notice the possible mistake. This panic can be disabled by setting m.DontCheckMethod to true prior to this call. See also MockTransport.RegisterResponder if a matcher is not needed. Note that github.com/maxatome/tdhttpmock provides powerful helpers to create matchers with the help of github.com/maxatome/go-testdeep. ```APIDOC ## MockTransport.RegisterMatcherResponder ### Description Adds a new responder, associated with a given HTTP method, URL (or path) and Matcher. When a request comes in that matches, the responder is called and the response returned to the client. ### Signature ```go func (m *MockTransport) RegisterMatcherResponder(method, url string, matcher Matcher, responder Responder) ``` ### Parameters #### Path Parameters - **method** (string) - Description: The HTTP method (e.g., GET, POST). If method is a lower-cased version of CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT or TRACE, a panic occurs unless m.DontCheckMethod is true. - **url** (string) - Description: The URL or path to match. If it begins with "=~", it's treated as a regular expression. Order of query parameters matters. - **matcher** (Matcher) - Description: The matcher to use for the request. - **responder** (Responder) - Description: The responder to call if the matcher matches. ``` -------------------------------- ### Basic HTTP Mocking with Exact and Regex URL Matching Source: https://pkg.go.dev/github.com/jarcoal/httpmock Demonstrates how to activate httpmock, set up responders for exact and regex URL matches, and retrieve call counts. Ensure httpmock.Activate() is called before registering responders and httpmock.DeactivateAndReset() is deferred. ```go func TestFetchArticles(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() // 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/ } ``` -------------------------------- ### MockTransport.GetTotalCallCount Source: https://pkg.go.dev/github.com/jarcoal/httpmock Gets the total number of calls that the MockTransport has handled since it was activated or reset. ```APIDOC ## func (*MockTransport) GetTotalCallCount ### Description GetTotalCallCount gets the total number of calls m has taken since it was activated or reset. ### Signature ```go func (m *MockTransport) GetTotalCallCount() int ``` ``` -------------------------------- ### GetTotalCallCount Source: https://pkg.go.dev/github.com/jarcoal/httpmock Gets the total number of calls httpmock has taken since it was first activated or last reset. ```APIDOC ## GetTotalCallCount ### Description Gets the total number of calls httpmock has taken since it was first activated or last reset. ### Signature ```go func GetTotalCallCount() int ``` ``` -------------------------------- ### Get Number of Responders - httpmock Source: https://pkg.go.dev/github.com/jarcoal/httpmock Returns the count of currently active responders. The special 'no responder' is excluded from this count. ```go func (m *MockTransport) NumResponders() int ``` -------------------------------- ### Import httpmock Package Source: https://pkg.go.dev/github.com/jarcoal/httpmock Import the httpmock package into your Go files. Ensure you run `go mod tidy` or `go test` to automatically populate your go.mod. ```go import "github.com/jarcoal/httpmock" ``` -------------------------------- ### Get the name of a Matcher Source: https://pkg.go.dev/github.com/jarcoal/httpmock The Name method returns the name associated with the Matcher. This can be useful for debugging or identifying specific matchers. ```go func (m Matcher) Name() string ``` -------------------------------- ### Advanced HTTP Mocking with Dynamic Responses Source: https://pkg.go.dev/github.com/jarcoal/httpmock Shows how to create dynamic HTTP responses using functions, including JSON responses and extracting data from regex submatches. This is useful for simulating more complex API behaviors. ```go func TestFetchArticles(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() // our database of articles articles := make([]map[string]any, 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]any{ "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]any) 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 }, ) // do stuff that adds and checks articles } ``` -------------------------------- ### Get Total Call Count Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the total number of HTTP calls handled by httpmock since it was activated or last reset. ```go func GetTotalCallCount() int ``` -------------------------------- ### Advanced HTTP Mocking with Custom Responders Source: https://pkg.go.dev/github.com/jarcoal/httpmock Illustrates advanced mocking using custom responder functions for dynamic responses, including JSON responses and request body matching. Shows how to extract data from request parameters. ```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 } ``` -------------------------------- ### Create Anonymous Matcher Source: https://pkg.go.dev/github.com/jarcoal/httpmock Demonstrates creating a new matcher with a nil match function, useful when registering responders with specific ordering rules. The matcher will be automatically named based on its creation context. ```go NewMatcher("original matcher name", nil) ``` -------------------------------- ### Get total call count for MockTransport Source: https://pkg.go.dev/github.com/jarcoal/httpmock GetTotalCallCount returns the total number of HTTP requests that the MockTransport has handled since it was activated or reset. ```go func (m *MockTransport) GetTotalCallCount() int ``` -------------------------------- ### Register Responder with String Source: https://pkg.go.dev/github.com/jarcoal/httpmock Register a responder for a specific HTTP method and URL. Query parameter order matters. Use '=~' prefix for regular expression matching. ```go func RegisterResponder(method, url string, responder Responder) ``` ```go httpmock.RegisterResponder("GET", "http://example.com/", httpmock.NewStringResponder(200, "hello world")) ``` ```go httpmock.RegisterResponder("GET", "/path/only", httpmock.NewStringResponder(200, "any host hello world")) ``` ```go httpmock.RegisterResponder("GET", "=~^/item/id/\d+\z", httpmock.NewStringResponder(200, "any item get")) ``` -------------------------------- ### Create a new Matcher Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use NewMatcher to create a Matcher. If the name is empty and the function is non-nil, a name is automatically generated. If the function is nil, it defaults to a Matcher that always succeeds. ```go func NewMatcher(name string, fn MatcherFunc) Matcher ``` -------------------------------- ### Register Responder with Query Parameter Match Source: https://pkg.go.dev/github.com/jarcoal/httpmock Adds a responder that matches a URL and its query parameters, ignoring query item order. Supports url.Values, map[string]string, or a query string. Path cannot be prefixed with '=~'. Registering a nil Responder removes an existing one. ```go func (m *MockTransport) RegisterResponderWithQuery(method, path string, query any, responder Responder) ``` -------------------------------- ### GetSubmatch Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a matching regexp. Must be used in Responders installed by RegisterRegexpResponder or RegisterResponder with a "=~" URL prefix. It panics if n < 1. ```APIDOC ## GetSubmatch ### Description Has to be used in Responders installed by RegisterRegexpResponder or RegisterResponder + "=~" URL prefix (as well as MockTransport.RegisterRegexpResponder or MockTransport.RegisterResponder). It allows to retrieve the n-th submatch of the matching regexp, as a string. It panics if n < 1. ### Signature ```go func GetSubmatch(req *http.Request, n int) (string, error) ``` ### Example ```go RegisterResponder("GET", `=~^/item/name/([^/]+)\z`, func(req *http.Request) (*http.Response, error) { name, err := GetSubmatch(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": 123, "name": name, }) }) ``` ``` -------------------------------- ### Register Responder with Regexp Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use RegisterRegexpResponder to add a responder that matches based on HTTP method and URL regexp. Responders are tested in registration order. Registering a nil Responder removes an existing one. ```go func (m *MockTransport) RegisterRegexpResponder(method string, urlRegexp *regexp.Regexp, responder Responder) ``` -------------------------------- ### Chain Responders with Then Source: https://pkg.go.dev/github.com/jarcoal/httpmock Creates a new Responder that sequentially calls chained Responders. The first Responder is called on the first invocation, the second on subsequent calls, and so on. Chaining is supported, but a Responder cannot be a parameter to another Then call to prevent runtime issues. This is useful for simulating sequences of responses. ```go func (r Responder) Then(next Responder) (x Responder) ``` ```go A := httpmock.NewStringResponder(200, "A") B := httpmock.NewStringResponder(200, "B") C := httpmock.NewStringResponder(200, "C") httpmock.RegisterResponder("GET", "/pipo", A.Then(B).Then(C)) http.Get("http://foo.bar/pipo") // A is called http.Get("http://foo.bar/pipo") // B is called http.Get("http://foo.bar/pipo") // C is called http.Get("http://foo.bar/pipo") // C is called, and so on ``` ```go A.Then(B).Then(C) // is OK ``` ```go A.Then(B.Then(C)) // panics as A.Then() parameter is another Then() call ``` -------------------------------- ### Register Responder with Regexp Matcher Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use RegisterRegexpMatcherResponder to add a responder that matches based on HTTP method, URL regexp, and a custom Matcher. Responders are tested in registration order. Registering a nil Responder removes an existing one. ```go func (m *MockTransport) RegisterRegexpMatcherResponder(method string, urlRegexp *regexp.Regexp, matcher Matcher, responder Responder) ``` -------------------------------- ### GetSubmatchAsUint Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a matching regexp as a uint64. Must be used in Responders installed by RegisterRegexpResponder or RegisterResponder with a "=~" URL prefix. It panics if n < 1. ```APIDOC ## GetSubmatchAsUint ### Description Has to be used in Responders installed by RegisterRegexpResponder or RegisterResponder + "=~" URL prefix (as well as MockTransport.RegisterRegexpResponder or MockTransport.RegisterResponder). It allows to retrieve the n-th submatch of the matching regexp, as a uint64. It panics if n < 1. ### Signature ```go func GetSubmatchAsUint(req *http.Request, n int) (uint64, error) ``` ### Example ```go RegisterResponder("GET", `=~^/item/id/(\d+)\z`, func(req *http.Request) (*http.Response, error) { id, err := GetSubmatchAsUint(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": id, "name": "The beautiful name", }) }) ``` ``` -------------------------------- ### Create HTTP Response with String Body Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use NewStringResponse to create an *http.Response with a specified status code and string body. For file content, use httpmock.File("body.txt").String(). ```go func NewStringResponse(status int, body string) *http.Response ``` ```go httpmock.NewStringResponse(200, httpmock.File("body.txt").String()) ``` -------------------------------- ### GetSubmatchAsInt Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a matching regexp as an int64. Must be used in Responders installed by RegisterRegexpResponder or RegisterResponder with a "=~" URL prefix. It panics if n < 1. ```APIDOC ## GetSubmatchAsInt ### Description Has to be used in Responders installed by RegisterRegexpResponder or RegisterResponder + "=~" URL prefix (as well as MockTransport.RegisterRegexpResponder or MockTransport.RegisterResponder). It allows to retrieve the n-th submatch of the matching regexp, as an int64. It panics if n < 1. ### Signature ```go func GetSubmatchAsInt(req *http.Request, n int) (int64, error) ``` ### Example ```go RegisterResponder("GET", `=~^/item/id/(\d+)\z`, func(req *http.Request) (*http.Response, error) { id, err := GetSubmatchAsInt(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": id, "name": "The beautiful name", }) }) ``` ``` -------------------------------- ### Register Matcher Responder With Query Go Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use RegisterMatcherResponderWithQuery to register a responder that matches a method, path, and query. The query matching is order-independent and supports url.Values, map[string]string, or a query string. Panics occur if the query type is unrecognized or the string cannot be parsed, or if the path is prefixed with "=~". ```go func RegisterMatcherResponderWithQuery(method, path string, query any, matcher Matcher, responder Responder) ``` -------------------------------- ### GetSubmatchAsFloat Source: https://pkg.go.dev/github.com/jarcoal/httpmock Retrieves the n-th submatch of a matching regexp as a float64. Must be used in Responders installed by RegisterRegexpResponder or RegisterResponder with a "=~" URL prefix. It panics if n < 1. ```APIDOC ## GetSubmatchAsFloat ### Description Has to be used in Responders installed by RegisterRegexpResponder or RegisterResponder + "=~" URL prefix (as well as MockTransport.RegisterRegexpResponder or MockTransport.RegisterResponder). It allows to retrieve the n-th submatch of the matching regexp, as a float64. It panics if n < 1. ### Signature ```go func GetSubmatchAsFloat(req *http.Request, n int) (float64, error) ``` ### Example ```go RegisterResponder("PATCH", `=~^/item/id/\d+\?height=(\d+(?:\.\d*)?)\z`, func(req *http.Request) (*http.Response, error) { height, err := GetSubmatchAsFloat(req, 1) // 1=first regexp submatch if err != nil { return nil, err } return NewJsonResponse(200, map[string]any{ "id": id, "name": "The beautiful name", "height": height, }) }) ``` ``` -------------------------------- ### Register Responder with Regexp and Matcher Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use this function to register a responder for a given HTTP method and URL regular expression, along with a custom matcher. Responders are evaluated in registration order. Registering a duplicate replaces the existing responder and resets statistics. Registering a nil responder removes it. Panics occur for invalid HTTP methods unless DefaultTransport.DontCheckMethod is true. ```go func RegisterRegexpMatcherResponder(method string, urlRegexp *regexp.Regexp, matcher Matcher, responder Responder) ``` -------------------------------- ### File.String Source: https://pkg.go.dev/github.com/jarcoal/httpmock Returns the content of the File as a string. ```APIDOC ## File.String ### Description Returns the content of the File as a string. ### Method Signature func (f File) String() string ``` -------------------------------- ### Register Responder with Exact URL Match Source: https://pkg.go.dev/github.com/jarcoal/httpmock Adds a responder for a specific HTTP method and URL. Query parameter order matters for exact matches. Registering a nil Responder removes an existing one. ```go func (m *MockTransport) RegisterResponder(method, url string, responder Responder) ``` -------------------------------- ### Create HTTP Response with XML Body Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use NewXmlResponse to create an *http.Response with a specified status code and an XML-encoded body from any Go type. For file content, use httpmock.File("body.xml"). ```go func NewXmlResponse(status int, body any) (*http.Response, error) ``` ```go httpmock.NewXmlResponse(200, httpmock.File("body.xml")) ``` -------------------------------- ### Create a new MockTransport Source: https://pkg.go.dev/github.com/jarcoal/httpmock NewMockTransport creates and returns a new *MockTransport instance with no responders initially registered. ```go func NewMockTransport() *MockTransport ``` -------------------------------- ### Get call count information for MockTransport Source: https://pkg.go.dev/github.com/jarcoal/httpmock GetCallCountInfo retrieves information about all calls caught by the MockTransport since activation or reset. It returns a map where keys are the concatenated method and URL, and values are the call counts. Regular expression responders generate two entries per call. ```go func (m *MockTransport) GetCallCountInfo() map[string]int ``` ```go map[string]int{ `GET http://z.com`: 1, `GET =~z\.com\z`: 1, } ``` -------------------------------- ### RegisterResponderWithQuery Source: https://pkg.go.dev/github.com/jarcoal/httpmock Similar to RegisterResponder, but matches queries without regard to parameter order. Supports various query types including url.Values, map[string]string, and raw query strings. Path matching does not support regex prefixes. ```APIDOC ## RegisterResponderWithQuery ### Description RegisterResponderWithQuery is same as MockTransport.RegisterResponder, but it doesn't depend on query items order. If query is non-nil, its type can be url.Values, map[string]string, or a string query. ### Method func (*MockTransport) RegisterResponderWithQuery(method, path string, query any, responder Responder) ### Parameters - **method** (string) - The HTTP method. - **path** (string) - The URL path (cannot be prefixed with "=~"). - **query** (any) - The query parameters. Can be url.Values, map[string]string, or a query string. - **responder** (Responder) - The callback function to handle the request. ### Notes - Unlike MockTransport.RegisterResponder, path cannot be prefixed by "=~". - Registering a nil Responder removes the existing one. - Method name case-insensitivity check can be disabled by setting m.DontCheckMethod to true. - See MockTransport.RegisterMatcherResponderWithQuery to also match on request header and/or body. ``` -------------------------------- ### GetCallCountInfo Source: https://pkg.go.dev/github.com/jarcoal/httpmock Gets information on all calls httpmock has caught since it was activated or reset. The info is returned as a map of the calling keys with the number of calls made to them as their value. The key is the method, a space, and the URL all concatenated together. Special case for regexp responders generates 2 entries per call. ```APIDOC ## GetCallCountInfo ### Description Gets the info on all the calls httpmock has caught since it was activated or reset. The info is returned as a map of the calling keys with the number of calls made to them as their value. The key is the method, a space, and the URL all concatenated together. As a special case, regexp responders generate 2 entries for each call. One for the call caught and the other for the rule that matched. ### Signature ```go func GetCallCountInfo() map[string]int ``` ### Example ```go RegisterResponder("GET", `=~z\.com\z`, NewStringResponder(200, "body")) http.Get("http://z.com") // Result: // map[string]int{ // `GET http://z.com`: 1, // `GET =~z\.com\z`: 1, // } ``` ``` -------------------------------- ### Register Responder with Regexp Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use this function to register a responder for a given HTTP method and URL regular expression. Responders are evaluated in registration order. Registering a duplicate replaces the existing responder and resets statistics. Registering a nil responder removes it. Panics occur for invalid HTTP methods unless DefaultTransport.DontCheckMethod is true. ```go func RegisterRegexpResponder(method string, urlRegexp *regexp.Regexp, responder Responder) ``` -------------------------------- ### Create XML Responder Source: https://pkg.go.dev/github.com/jarcoal/httpmock NewXmlResponder creates a responder with an XML body and a specified status code. For file content, use httpmock.File("body.xml"). ```go func NewXmlResponder(status int, body any) (Responder, error) ``` ```go httpmock.NewXmlResponder(200, httpmock.File("body.xml")) ``` -------------------------------- ### Define File Content for Mock Responses Source: https://pkg.go.dev/github.com/jarcoal/httpmock The File type represents a file name. Its String() method loads and returns the file's content as a string, useful for creating string responses. To print the file name itself, cast it to string. ```go file := httpmock.File("file.txt") fmt.Printf("file: %s\n", file) ``` ```go file := httpmock.File("file.txt") fmt.Printf("file: %s\n", string(file)) ``` -------------------------------- ### String Method for RouteKey Source: https://pkg.go.dev/github.com/jarcoal/httpmock/internal Implements the Stringer interface for RouteKey, providing a string representation of the route key. ```go func (r RouteKey) String() string ``` -------------------------------- ### Responder.Then Source: https://pkg.go.dev/github.com/jarcoal/httpmock Chains another responder to be called after the current one. ```APIDOC ## func (r Responder) Then(next Responder) (x Responder) ### Description Chains another responder to be called after the current one. ### Method Responder.Then ### Parameters #### Path Parameters - **next** (Responder) - Required - The next responder in the chain. ``` -------------------------------- ### Matcher.And Source: https://pkg.go.dev/github.com/jarcoal/httpmock Combines multiple Matchers using a logical AND operation. ```APIDOC ## Matcher.And ### Description Combines multiple Matchers using a logical AND operation. ### Method Signature func (m Matcher) And(ms ...Matcher) Matcher ``` -------------------------------- ### Create Responder from Multiple Responses Source: https://pkg.go.dev/github.com/jarcoal/httpmock Wraps a list of *http.Response objects into a Responder. Each response is returned sequentially. If called more times than the number of responses, an error is thrown. Ensure response bodies can be read multiple times if not generated by httpmock. ```go func ResponderFromMultipleResponses(responses []*http.Response, fn ...func(...any)) Responder ``` ```go httpmock.RegisterResponder("GET", "/foo/bar", httpmock.ResponderFromMultipleResponses( []*http.Response{ httpmock.NewStringResponse(200, `{"name":"bar"}`), httpmock.NewStringResponse(404, `{"mesg":"Not found"}`), }, t.Log), ) ``` -------------------------------- ### Register Responder with Regex Submatch Int Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use MustGetSubmatchAsInt to retrieve the n-th regexp submatch as an int64. It panics if the submatch is not found or if the format is not a valid int64. It requires n to be 1 or greater. ```go RegisterResponder("GET", `=~^/item/id/(\d+)\z`, func(req *http.Request) (*http.Response, error) { id := MustGetSubmatchAsInt(req, 1) // 1=first regexp submatch return NewJsonResponse(200, map[string]any{ "id": id, "name": "The beautiful name", }) }) ``` -------------------------------- ### MatcherFunc.Or Source: https://pkg.go.dev/github.com/jarcoal/httpmock Combines the current MatcherFunc with others. The resulting MatcherFunc succeeds if any of the combined MatcherFuncs succeed. If any of the combined MatcherFuncs are nil, the result is nil (which is considered succeeding). ```APIDOC ## func (MatcherFunc) Or ### Description Or combines mf and all mfs in a new MatcherFunc. This new MatcherFunc succeeds if one of mf or mfs succeeds. Note that as a nil MatcherFunc is considered succeeding, if mf or one of mfs items is nil, nil is returned. ### Signature ```go func (mf MatcherFunc) Or(mfs ...MatcherFunc) MatcherFunc ``` ``` -------------------------------- ### Register Matcher Responder With Query Source: https://pkg.go.dev/github.com/jarcoal/httpmock Use RegisterMatcherResponderWithQuery for flexible query matching, especially when query item order is not guaranteed. It supports url.Values, map[string]string, or raw query strings. Panics occur for unrecognized query types or unparseable strings. Path matching does not support regexp prefixes. ```go func (m *MockTransport) RegisterMatcherResponderWithQuery(method, path string, query any, matcher Matcher, responder Responder) ``` -------------------------------- ### RegisterMatcherResponderWithQuery Source: https://pkg.go.dev/github.com/jarcoal/httpmock Registers a mock response for a given HTTP method, path, and query parameters, using a Matcher. ```APIDOC ## RegisterMatcherResponderWithQuery ### Description Registers a mock response for a given HTTP method, path, and query parameters, using a Matcher. ### Function Signature func RegisterMatcherResponderWithQuery(method, path string, query any, matcher Matcher, responder Responder) ``` -------------------------------- ### Activate Source: https://pkg.go.dev/github.com/jarcoal/httpmock Activates the global mock transport. This should be called at the beginning of your tests to enable mocking. ```APIDOC ## Activate ### Description Activates the global mock transport. This should be called at the beginning of your tests to enable mocking. ### Function Signature func Activate(t ...testing.TB) ``` -------------------------------- ### Create a new Matcher with a specific name Source: https://pkg.go.dev/github.com/jarcoal/httpmock WithName returns a new Matcher based on an existing one, but with a specified name. This allows for more descriptive naming of matchers. ```go func (m Matcher) WithName(name string) Matcher ``` -------------------------------- ### NewMatcher Source: https://pkg.go.dev/github.com/jarcoal/httpmock Creates a new Matcher with a given name and a MatcherFunc. If the name is empty and the function is not nil, a name is automatically generated. If the function is nil, it defaults to a Matcher that always succeeds. ```APIDOC ## func NewMatcher ### Description NewMatcher returns a Matcher. If name is empty and fn is non-nil, a name is automatically generated. When fn is nil, it is a default Matcher: its name can be empty. Automatically generated names have the form: `~HEXANUMBER@PKG.FUNC() FILE:LINE` ### Signature ```go func NewMatcher(name string, fn MatcherFunc) Matcher ``` ```