I do not want to repeat this code every time I want to create a session :
var shash, _ = bcrypt.GenerateFromPassword([]byte(os.Getenv("SESSION_KEY")), bcrypt.DefaultCost)
var store = sessions.NewCookieStore(shash)
session, serr := store.Get(r, "session-name")
if serr != nil {
....
}
So, I created a function in a file inc/inc.go
in package inc
:
func initSession(r *http.Request){
var shash, _ = bcrypt.GenerateFromPassword([]byte(os.Getenv("SESSION_KEY")), bcrypt.DefaultCost)
var store = sessions.NewCookieStore(shash)
session, serr := store.Get(r, "session-name")
if serr != nil {
log.Fatal(serr)
return
}
}
The function initSession
initializes the session object.
There are also global variables in the file inc.go
, example :
var DbName string = "dbname"
var DbUser string = "user"
var DbPass string = "pass"
var DbHost string ="localhost"
So that I can access these variables from any file that imports package inc
.
My problem is that I do not know how to make session
in the function initSession global like the other variables? so that I can access it using inc.Session
?
Also, how do I declare the variable with var Session type
, given that I am using package github.com/gorilla/sessions
, what should I replace type
with?