I have written below code to create the dbSession
only once
but I am getting below warning from golang ci-lint
once
is a global variable (gochecknoglobals)
exported func NewDbSession
returns unexported type dbSession
, which can be annoying to use (golint)
var (
once sync.Once
dbSess dbSession
)
type dbSession struct {
session *gocql.Session
}
func NewDbSession() dbSession {
once.Do(func() {
if dbSess.session == nil {
session, err := createSession()
if err != nil {
panic(err)
}
dbSess = dbSession{session: session}
}
})
return dbSess
}
func createSession() {
....
}
This is supposed to be an idiomatic way of implementing the singleton pattern in golang.
-
Firstly, how do we supposed to implement singleton without a global variable?
-
Secondly, sometimes we don’t want to expose the type with the exported function.
Is it a hard and fast rule in golang to have an exported return type for an exported function which returns?