Before starting using sessions in golang I need answers to some questions
session example
import "github.com/gorilla/sessions"
var store = sessions.NewCookieStore([]byte("33446a9dcf9ea060a0a6532b166da32f304af0de"))
func Handler(w http.ResponseWriter, r *http.Request){
session, _ := store.Get(r, "session-name")
session.Values["foo"] = "bar"
session.Values[42] = 43
session.Save(r, w)
fmt.Fprint(w, "Hello world :)")
}
func main(){
store.Options = &sessions.Options{
Domain: "localhost",
Path: "/",
MaxAge: 60 * 15,
Secure: false,
HttpOnly: true,
}
}
Q1:
Is it possible to add multiple sessions on the same domain with different names?
session1, _ := store.Get(r, "session-name-1")
session2, _ := store.Get(r, "session-name-2")
When do you need multiple sessions on the same domain?
Q2:
What is the best practice to get the variables from the session? my_session_var = session.Values["foo"]
Q3:
How to check if the session is saved correctly? If you access the same map
to both set and get variables?
update
package main
import (
"github.com/gorilla/sessions"
)
var (
store = sessions.NewCookieStore([]byte("33446a9dcf9ea060a0a6532b166da32f304af0de"))
)
type handler func(w http.ResponseWriter, r *http.Request, s *sessions.Session)
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request){
session, _ := store.Get(r, "session-name")
h(w, r, session)
}
func Handler_404(w http.ResponseWriter, r *http.Request, s *sessions.Session){
fmt.Fprint(w, "Oops, something went wrong!")
}
error
# command-line-arguments
.\mux.go:101: cannot convert Handler_404 (type func(http.ResponseWriter, *http.Request, *sessions.Session)) to type http.HandlerFunc