SessionStart 函数返回的是一个满足 Session 接口的变量,那么我们该如何用他来对
session 数据进行操作呢?
上面的例子中的代码 session.Get(“uid”)已经展示了基本的读取数据的操作,现在我们再来
看一下详细的操作:
func count(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
createtime := sess.Get(“createtime”)
if createtime == nil {
sess.Set(“createtime”, time.Now().Unix())
} else if (createtime.(int64) + 360) < (time.Now().Unix()) {
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}
ct := sess.Get(“countnum”)
if ct == nil {
sess.Set(“countnum”, 1)
} else {
sess.Set(“countnum”, (ct.(int) + 1))
}
t, _ := template.ParseFiles(“count.gtpl”)
w.Header().Set(“Content-Type”, “text/html”)
t.Execute(w, sess.Get(“countnum”))
}
通过上面的例子可以看到,Session 的操作和操作 key/value 数据库类似:Set、Get、Delete
等操作
因为 Session 有过期的概念,所以我们定义了 GC 操作,当访问过期时间满足 GC 的触发
条件后将会引起 GC,但是当我们进行了任意一个 session 操作,都会对 Session 实体进行
更新,都会触发对最后访问时间的修改,这样当 GC 的时候就不会误删除还在使用的
Session 实体。
session 重置
我们知道,Web 应用中有用户退出这个操作,那么当用户退出应用的时候,我们需要对该
用户的 session 数据进行销毁操作,上面的代码已经演示了如何使用 session 重置操作,
下面这个函数就是实现了这个功能:
//Destroy sessionid
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r
*http.Request){
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == “” {
return
} else {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionDestroy(cookie.Value)
expiration := time.Now()
cookie := http.Cookie{Name: manager.cookieName, Path: “/”,
HttpOnly: true, Expires: expiration, MaxAge: -1}
http.SetCookie(w, &cookie)
}
}
golang从0到1实战系统六十一:操作值:设置、读取和删除
本文详细介绍了如何在GoWeb应用中使用SessionStart函数对会话数据进行操作,包括Set、Get、Delete等,以及如何处理Session过期和用户退出时的Session销毁。还讨论了SessionGC机制和cookie的管理。

被折叠的 条评论
为什么被折叠?



