I am using redis to store sessions for my Go simple web app. For this, I only want a single session to access the redis connection at a time. I searched up on implementing singleton objects in Go and followed. This is the code I'm currently implementing:
package Datab
import (
"github.com/gomodule/redigo/redis"
)
type cache struct {
Conn redis.Conn
}
var singleCache *cache = nil
func GetSessionCache() *cache {
if singleCache == nil {
singleCache := &cache{}
singleCache.Conn, _ = redis.DialURL("redis://localhost")
// ^ SINGLECACHE IS NOT NIL HERE.
}
return singleCache
// ^ SAYS THIS IS NIL!
}
package Handler
import (
Datab "videodoox/DB" // this file contains the redis connection implementation
)
connStru := *Datab.GetSessionCache()
cache := connStru.Conn
connStru2 := *Datab.GetSessionCache()
cache2: = connStru.Conn
// ^ THIS CONNECTION HERE IS A COMPLETELY NEW INSTANCE.
Everytime I get the connection, the redis connection file creates a new instance of the connection. How do I create a new connection once and just return that connection everytime? Thanks!
Comments to the initial question solve the issue, but just to provide a complete solution your code can look like:
package Datab
import (
"sync"
"github.com/gomodule/redigo/redis"
)
type cache struct {
Conn redis.Conn
}
var singleCache *cache
var initOnce sync.Once
func GetSessionCache() *cache {
initOnce.Do(func() {
singleCache := &cache{}
singleCache.Conn, _ = redis.DialURL("redis://localhost")
})
return singleCache
}
Just a couple of extra notes:
nil
as an initial value of pointers, zero value for them is nil
by default (var singleCache *cache
vs var singleCache *cache = nil
).redis.DialURL
and not just skip it with _
.