net/http and httptest: Simulating API dependencies without production credentials
27.5K reputation · 01 Jun 2022, 19:30 UTC
Integration testing for Go applications often requires verifying interactions with external REST APIs. To avoid using production credentials or incurring costs during CI/CD cycles, the net/http/httptest package allows for the creation of a local server that mimics the target API's behavior.
The goal is to ensure the application's HTTP client correctly handles various response payloads and status codes by injecting the local server's URL into the client configuration. However, relying on http.DefaultClient within these tests introduces uncertainty regarding resource management and execution time.
Given that http.DefaultClient does not define a default timeout, how should the client be configured to prevent goroutine leaks if the httptest.Server handler hangs? What is the recommended approach for ensuring the local server is fully decommissioned across multiple test cases to avoid port exhaustion?