go get -u -v github.com/go-session/mongo/v3
package main
import (
"context"
"fmt"
"net/http"
"github.com/go-session/mongo/v3"
"github.com/go-session/session/v3"
)
func main() {
session.InitManager(
session.SetStore(mongo.NewStore("mongodb://127.0.0.1:27017","test","session")),
)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
store, err := session.Start(context.Background(), w, r)
if err != nil {
fmt.Fprint(w, err)
return
}
store.Set("foo", "bar")
err = store.Save()
if err != nil {
fmt.Fprint(w, err)
return
}
http.Redirect(w, r, "/foo", 302)
})
http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
store, err := session.Start(context.Background(), w, r)
if err != nil {
fmt.Fprint(w, err)
return
}
foo, ok := store.Get("foo")
if ok {
fmt.Fprintf(w, "foo:%s", foo)
return
}
fmt.Fprint(w, "does not exist")
})
http.ListenAndServe(":8080", nil)
}
$ go build server.go
$ ./server
http://localhost:8080