I have main package (main.go):
package main
import (
"github.com/gorilla/sessions"
...
)
func main() {
var store = sessions.NewCookieStore([]byte("secret"))
http.HandleFunc("/", routes.Index)
http.ListenAndServe(":8080", nil)
...
And I have another package (index.go):
package routes
import (
"github.com/gorilla/sessions"
..
)
func Index(res http.ResponseWriter, req *http.Request) {
session, _ := store.Get(req, "session-name")
...
How can I get session value from another package? Or should I pass it to my Handler (if yes how to do it?).
I am new in Golang. Please, help.
I generally wrap my dependencies in their own package, which let's me abstract away some of the common things I do. For sessions, I usually use the same session name most of the time, so I would usually have something like this:
And then anywhere else you can just import your own sessions package:
Even better would be to only return an
interface
of some sort from sessions, and completely wrap thegorilla/sessions
so that aren't dependent on it anywhere except for your own sessions package.