When I started picking up the go language years ago, things that stood out to me immediately were the
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
The two things which stand out for me are:
- Interface Design.
The primary constructs you’ll interact with are pretty limited:
To build your service:
To handle requests:
To build a client:
In total, we’re looking at 7 core primitives to build a client and server — which isn’t a lot!
When it comes to building HTTP services, the main things users need likely fall into two buckets:
- Defining what handlers to run based on a method, or path.
- Defining middleware to be executed.
Here’s an example showing this composability in action  :
- In this miniature example, we can see that the
authenticatemiddleware is doing authentication for us.
- Similarly, we handle path routing by specifying the prefix to use for each handler.
Testing your service
From this example, testing your service would be pretty straightforward:
As we can see, getting started with the
net/http package is extremely simple but packs a lot of punch.
In a followup article, I’ll share more about using
http.Client as the unit of integration for building HTTP clients.
- : For brevity, we’ve chosen to use
http.HandlerFuncin our code example, but in practice, or in production, we’d always want to use
http.Handlersince we can convert an
http.HandlerFuncto it easily.
- : Similarly, we would want to handle graceful shutdown of the http server so we’d want to utilize the Shutdown method of the