How to Test HTTP Outbound in Go Using Just the Standard Library

Jose Sitanggang
Stackademic
Published in
9 min readApr 15, 2024

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 gotips

We need to check out this specific version to ensure we all have the same code.

git checkout 3420b1c
cd how-to-test-http-outbound

Let’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:

  1. The GetPost function retrieves a post by ID.
  2. The GetPosts function 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.

Testing Using httptest.Server

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

No responses yet

What are your thoughts?