Using the net/http package in go

What I love about net/http

The two things which stand out for me are:

  1. Interface Design.
  2. Composability

Interface Design

The primary constructs you’ll interact with are pretty limited:

http.Handler
http.HandlerFunc
http.Server
http.ResponseWriter
http.Request
http.Client
http.Transport

Composability

When it comes to building HTTP services, the main things users need likely fall into two buckets:

  1. Defining what handlers to run based on a method, or path.
  2. Defining middleware to be executed.
  • 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

From this example, testing your service would be pretty straightforward:

Conclusion

As we can see, getting started with the net/http package is extremely simple but packs a lot of punch.

Footnotes

  • [1]: For brevity, we’ve chosen to use http.HandlerFunc in our code example, but in practice, or in production, we’d always want to use http.Handler since we can convert an http.HandlerFunc to it easily.
  • [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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cyril David

Cyril David

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