Sharing data between handlers

If we want to keep our handlers as pure as the http.Handler interface from the Go standard library, while still extracting common functionality into our own methods, we need a way of sharing data between handlers. The HandlerFunc signature that follows tells us that we are only allowed to pass in an http.ResponseWriter object and an http.Request object, and nothing else:

type HandlerFunc func(http.ResponseWriter, *http.Request)

This means that we cannot create and manage database session objects in one place and pass them into our handlers, which is ideally what we want to do.

Instead, we are going to implement an in-memory map of per-request data, and provide an easy way for handlers to access it. Alongside the twittervotes ...

Get Go Programming Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.