No description, website, or topics provided.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.travis.yml
LICENSE
README.md
glue.go
glue_test.go

README.md

glue - Middleware data sharing

Build Status

What?

In essence, glue replaces the default http.ResponseWriter with a simple wrapper. This wrapper holds a map[string]interface{} named Vars and is created on every new request. Vars is used as a classic context map, like gorilla/context.

Additionally, this wrapper contains a pointer to a user defined environment object, which kind of acts as a dependency injection container, named Env.

For an in-depth explanation, see my blog post.

Usage

First of all, you should go get this package:

go get github.com/fdborn/glue

Then import it:

import "github.com/fdborn/glue

As the first real step, you want to create your very own environment. This structure holds all your important singletons and objects, such as the database-manager, worker-queue etc.:

type Environment struct {
  ImportantValue int
}

Now you create a new glue instance with a pointer to your environment:

env := Environment{ImportantValue: 42}
g := glue.New(&env)

Finally use the Apply method of the newly created object as the first http.Handler in your chain of handlers:

http.Handle("/", g.Apply(OptionalMiddleware(IndexHandler)))

Bonus points if you saw that Apply has the common (http.Handler) http.Handler signature. This makes it compatible with most of the existing middleware solutions. For example Alice:

chain := alice.New(g.Apply, OptionalMiddleware)
http.Handle("/", chain.Then(IndexHandler))

Now for your middleware:

func OptionalMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    context := glue.Extract(w)
    env := context.Env.(*Environment)

    context.Vars["SomeValue"] = "foo"
    context.Vars["ImportantValue"] = env.ImportantValue
  })
}

You can use glue.Extract to get glues Context object. This objects holds a map with request-specific values and a pointer to your specified environment (although you still have make a type assertion).