Go Pattern: Scoped HTTP Handlers
A tiny yet powerful abstraction which I don’t see enough is to create HTTP handler wrappers which contains everything it needs:
- A Request struct
- A Response struct
- HTTP Handler function
- Dependencies struct(e.g access to database)
This is how they look like:
|
|
This is nice because it makes the code highly readable in a single glance, especially if you have tens or hundreds of such handlers. It looks cleaner too since we don’t have a method receiver for every handler. Since we can’t have a pointer receiver in this pattern, we won’t be accidentally modifying anything. All state is request-scoped.
Adding a new dependency is only a matter of modifying the context struct.It doesn’t adversly affect code reusability either as we can embed common structs in req
or resp
structs:
|
|
Also, better copiability :)