How to Test HTTP Outbound in Go Using Just the Standard Library
The Go standard library is rich and powerful, but we often find ourselves needing third-party libraries to test HTTP outbound. Similar to testing an HTTP handler with the httptest package, we can also test HTTP outbound either with httptest or by extending the http.RoundTripper package. This article will demonstrate how to test HTTP outbound in Go.
Prepare the Playground
To ensure we’re on the same page, let’s clone this repository to use as our base code.
git clone git@github.com:josestg/gotips.git
cd gotipsWe need to check out this specific version to ensure we all have the same code.
git checkout 3420b1c
cd how-to-test-http-outboundLet’s focus on the http_outbound.go file, which contains the client code for calling the external API ( jsonplaceholder.typicode.com)
For simplicity, we have two functions in the http_outbound.go file:
- The
GetPostfunction retrieves a post by ID. - The
GetPostsfunction retrieves all posts.
Both of these functions utilize the same base function fetch, which performs the actual HTTP request and decodes the response. The code should be self-explanatory, so let's proceed to the next part.