stretchr / goweb

A lightweight RESTful web framework for Go
632 stars 61 forks source link

Example for injecting database into context #68

Closed drewblas closed 10 years ago

drewblas commented 10 years ago

Is there a way to maintain a database connection (using https://github.com/vmihailenco/redis/tree/master/v2 for example) and then inject access to it into the context so that each request can use the connection (thread-safely) without having to reconnect?

If you have an example of the correct way of doing this, it'd be greatly appreciated.

matryer commented 10 years ago

You can do this:

const dataKeyConnection string = "connection"
goweb.DefaultHttpHandler().Data.Set(dataKeyConnection, connectionObject)

And then it will be available to all of your contexts:

connectionObject := ctx.Data().Get(dataKeyConnection)

BUT normally sharing a connection like this is troublesome, the framework might provide some kind of copy or sub-connection mechanism that you should consider.

drewblas commented 10 years ago

Thanks very much. The client offers a "Copy" function, so that seems to be ok. But when I get the object back from the ctx.Data().Get(...) it comes back as an objx.Value. How do I cast that back into the connection object type that I originally put in?

matryer commented 10 years ago

You can use the Data() call on objx.Value.

obj := ctx.Data().Get(...).Data().(*yourType)
matryer commented 10 years ago

... I know it seems insane, but objx actually supports lots of types and does the casting for you:

var s string
s = data.Get("address.city").Str()
matryer commented 10 years ago

p.s. I would recommend having a MapBefore that configures the database connection for you and saves the copy in the context data. Then you don't have to duplicate code.