Closed drewblas closed 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.
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?
You can use the Data()
call on objx.Value
.
obj := ctx.Data().Get(...).Data().(*yourType)
... 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()
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.
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.