Dependency Injection and Testability in a Go Webservice

Filip Sufitchi
7 min readJan 22, 2020

TL;DR: Rationale and recommendations on how to assemble a well-behaved HTTP API in Go, using Wire as the glue. Just looking for the finished “demo”? See here.

Let’s sit down and write a new feature for a website: a visitor counter. This is just a small API service, that saves a single number in a database, and serves/increments it via a single endpoint. So, we sit down and hammer out something like this:

It’s succinct, it works, so we’re done, right? Not quite. No good code is done without testing, so let’s do that.

Where do we even get started? This is a mess!

  • A bunch of the logic is in the main() function, which can’t be tested without launching a fully-fledged web server. Can we even count on being able to launch a server (or even open a net port) on any machine we’re testing this on?
  • The state of our routing is contained in global variables in Go’s net/http package, which is rather inconvenient.
  • Code behavior depends on environment variables, which might be…

--

--