go get -u github.com/no-src/nssession
package main
import (
"net/http"
"time"
"github.com/no-src/log"
"github.com/no-src/nssession"
"github.com/no-src/nssession/store"
"github.com/no-src/nssession/store/memory"
)
func main() {
// initial default session config
c := &nssession.Config{
Connection: "memory:",
Expiration: time.Hour,
Store: store.NewStore(memory.Driver),
}
err := nssession.InitDefaultConfig(c)
if err != nil {
log.Error(err, "init the default config error")
return
}
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
// get session component
session, err := nssession.Default(request, writer)
if err != nil {
log.Error(err, "get session component error")
return
}
// set session data
k := "hello"
var v string
err = session.Set(k, "world")
if err != nil {
log.Error(err, "set session data error")
return
}
// get session data
err = session.Get(k, &v)
if err != nil {
log.Error(err, "get session data error")
return
}
log.Info("get the session data success, k=%s v=%s", k, v)
// remove session data
err = session.Remove(k)
if err != nil {
log.Error(err, "remove session data error")
return
}
// clear all session data for the current session
err = session.Clear()
if err != nil {
log.Error(err, "clear session data error")
return
}
})
http.ListenAndServe(":8080", nil)
}