Book Image

Go Programming Blueprints

By : Mat Ryer
Book Image

Go Programming Blueprints

By: Mat Ryer

Overview of this book

Table of Contents (17 chapters)
Go Programming Blueprints
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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 and counter folders, create a new folder called api and create a new file called vars.go inside it. Add the following code to the file:

package main
import (
  "net/http"
  "sync"
)
var vars map[*http.Request]map[string]interface{}
var varsLock...