Go HTTP Middleware Explained

Stop copying and pasting the same code into every single handler.

If you need to check authentication, log request duration, or add a unique ID to every request, do not write that logic inside your business handlers. If you have 20 handlers, you have 20 places to update when your auth logic changes. This is a maintenance nightmare.

Middleware solves this. You write the logic once. You wrap your handlers. You never touch it again.

What is Middleware?

In Go, middleware is a function that: • Accepts an http.Handler. • Returns a new http.Handler. • Performs actions before or after the original handler runs.

Think of it like an onion. Each layer wraps the next. The request goes through each layer on the way in. The response goes through each layer on the way out.

What you will learn:

• The http.Handler interface foundation. • How to build custom middleware from scratch. • How to chain multiple layers together. • How to pass data through the chain using context. • Advanced tips like ordering and panic recovery.

Key Takeaways:

• Order matters. If one middleware sets a value in the context, the next middleware in the chain must be the one to read it. If you swap them, the data will be empty.

• Always return after an early exit. If you find an error and send an http.Error, call return immediately. If you call next.ServeHTTP after sending an error, your server will panic.

• Use custom types for context keys. Do not use plain strings for keys. This prevents different packages from overwriting each other's data.

• Use a wrapper to capture data. Since the standard http.ResponseWriter does not let you read the status code after it is written, you must create a custom struct to intercept and save it for your logs.

Build a solid foundation for your Go HTTP servers by mastering these patterns.

Source: https://dev.to/ferztyle/go-http-middleware-explained-what-it-is-how-it-works-and-how-to-build-your-own-1ma7