Using the net/http package in go

When I started picking up the go language years ago, things that stood out to me immediately were the io and net/http packages. Both of those packages were extremely well done and minimal in the amount of interfaces they exposed to the user.

What I love about net/http

  1. Interface Design.
  2. Composability

Interface Design

To build your service:

http.Handler
http.HandlerFunc
http.Server

To handle requests:

http.ResponseWriter
http.Request

To build a client:

http.Client
http.Transport

In total, we’re looking at 7 core primitives to build a client and server — which isn’t a lot!

Composability

  1. Defining what handlers to run based on a method, or path.
  2. Defining middleware to be executed.

Here’s an example showing this composability in action [1] [2]:

  • In this miniature example, we can see that the authenticate middleware is doing authentication for us.
  • Similarly, we handle path routing by specifying the prefix to use for each handler.

Testing your service

Conclusion

In a followup article, I’ll share more about using http.Client as the unit of integration for building HTTP clients.

Footnotes

  • [2]: Similarly, we would want to handle graceful shutdown of the http server so we’d want to utilize the Shutdown method of the http.Server primitive.

software engineer at auth0, writing code for humans, with humans.