修改了一些代码的错误

This commit is contained in:
xiemengjun
2012-09-27 00:06:23 +08:00
parent e6c3436bb8
commit 9a17a3f6e5
3 changed files with 137 additions and 126 deletions

130
6.2.md
View File

@@ -33,27 +33,27 @@ session的基本原理是由服务器为每个会话维护一份信息数据
定义一个全局的session管理器
type SessionManager struct {
type Manager struct {
cookieName string //private cookiename
lock sync.Mutex // protects session
provider Provider
maxLifeTime int64
maxlifetime int64
}
func NewSessionManager(provideName, cookieName string, maxLifeTime int64) (*SessionManager, error) {
func NewManager(provideName, cookieName string, maxlifetime int64) (*Manager, error) {
provider, ok := provides[provideName]
if !ok {
return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
}
return &SessionManager{provider: provider, cookieName: cookieName, maxLifeTime: maxLifeTime}, nil
}
return &Manager{provider: provider, cookieName: cookieName, maxlifetime: maxlifetime}, nil
}
Go实现整个的流程应该也是这样的在main包中创建一个全部的session管理器
var globalSessions *SessionManager
var globalSessions *session.Manager
//然后在init函数中初始化
func init() {
globalSessions = NewSessionManager("memory","gosessionid",3600)
globalSessions = NewManager("memory","gosessionid",3600)
}
我们知道session是保存在服务器端的数据它可以以任何的方式存储比如存储在内存、数据库或者文件中。因此我们抽象出一个Provider接口用以表征session管理器底层存储结构。
@@ -61,7 +61,7 @@ Go实现整个的流程应该也是这样的在main包中创建一个全部
type Provider interface {
SessionInit(sid string) (Session, error)
SessionRead(sid string) (Session, error)
SessionDestroy(sid string) bool
SessionDestroy(sid string) error
SessionGC(maxLifeTime int64)
}
@@ -70,12 +70,13 @@ Go实现整个的流程应该也是这样的在main包中创建一个全部
- SessionDestroy函数用来销毁sid对应的Session变量
- SessionGC根据maxLifeTime来删除过期的数据
那么Session接口需要实现什么样的功能呢有过Web开发经验的读者知道对Session的处理基本就 设置值、读取值、删除值这三个操作所以我们的Session接口也就实现这个操作。
那么Session接口需要实现什么样的功能呢有过Web开发经验的读者知道对Session的处理基本就 设置值、读取值、删除值以及获取当前sessionID这四个操作所以我们的Session接口也就实现这个操作。
type Session interface {
Set(key interface{}, value interface{}) //set session value
Get(key interface{}) interface{} //get session value
Del(key interface{}) bool //delete session value
Set(key, value interface{}) error //set session value
Get(key interface{}) interface{} //get session value
Delete(key interface{}) error //delete session value
SessionID() string //back current sessionID
}
>以上设计思路来源于database/sql/driver先定义好接口然后具体的存储session的结构实现相应的接口并注册后相应功能这样就可以使用了以下是用来随需注册存储session的结构的Register函数的实现。
@@ -99,30 +100,29 @@ Go实现整个的流程应该也是这样的在main包中创建一个全部
Session ID是用来识别访问Web应用的每一个用户因此必须保证它是全局唯一的GUID下面代码展示了如何满足这一需求
func (this *SessionManager) sessionId() string {
func (manager *Manager) sessionId() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return string(b)
return base64.URLEncoding.EncodeToString(b)
}
###session创建
我们需要为每个来访用户分配或获取与他相关连的Session以便后面根据Session信息来验证操作。SessionStart这个函数就是用来检测是否已经有某个Session与当前来访用户发生了关联如果没有则创建之。
func (this *SessionManager) SessionStart(w ResponseWriter, r *http.Request) (session Session) {
this.lock.Lock()
defer this.lock.Unlock()
cookie, err := r.Cookie(this.cookieName)
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
manager.lock.Lock()
defer manager.lock.Unlock()
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
sid := this.sessionId()
session = this.provider.SessionInit(sid)
expiration := time.Now()
expiration.Add(time.Duration(this.maxlifetime))
cookie := http.Cookie{Name: this.cookieName, Value: sid, Expires: expiration}
sid := manager.sessionId()
session, _ = manager.provider.SessionInit(sid)
cookie := http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxlifetime)}
http.SetCookie(w, &cookie)
} else {
session = this.provider.SessionRead(cookie.Value)
sid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRead(sid)
}
return
}
@@ -130,19 +130,15 @@ Session ID是用来识别访问Web应用的每一个用户因此必须保证
我们用前面login操作来演示session的运用
func login(w http.ResponseWriter, r *http.Request) {
session:=globalSessions.SessionStart(w,r)
fmt.Println("method:", r.Method) //获取请求的方法
sess := globalSessions.SessionStart(w, r)
r.ParseForm()
if r.Method == "GET" {
if session.Get("uid").(string) != "" {
t, _ := template.ParseFiles("main.gtpl")
}else{
t, _ := template.ParseFiles("login.gtpl")
}
t.Execute(w, nil)
t, _ := template.ParseFiles("login.gtpl")
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("username"))
} else {
//请求的是登陆数据,那么执行登陆的逻辑判断
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
sess.Set("username", r.Form["username"])
http.Redirect(w, r, "/", 302)
}
}
@@ -151,44 +147,44 @@ SessionStart函数返回的是一个满足Session接口的变量那么我们
上面的例子中的代码`session.Get("uid")`已经展示了基本的读取数据的操作,现在我们再来看一下详细的操作:
func login(w http.ResponseWriter, r *http.Request) {
session:=globalSessions.SessionStart(w,r)
fmt.Println("method:", r.Method) //获取请求的方法
if r.Method == "GET" {
if session.Get("uid").(string) != "" {
session.Del("password")
t, _ := template.ParseFiles("main.gtpl")
}else{
t, _ := template.ParseFiles("login.gtpl")
}
t.Execute(w, nil)
} else {
//请求的是登陆数据,那么执行登陆的逻辑判断
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
session.Set("username",r.Form["username"])
session.Set("password",r.Form["password"])
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、Del等操作
通过上面的例子可以看到Session的操作和操作key/value数据库类似:Set、Get、Delete等操作
因为Session有过期的概念所以我们定义了GC操作当访问过期时间满足GC的触发条件后将会引起GC但是当我们进行了任意一个session操作都会对Session实体进行更新都会触发对最后访问时间的修改这样当GC的时候就不会误删除还在使用的Session实体。
###session重置
我们知道Web应用中有用户退出这个操作那么当用户退出应用的时候我们需要对该用户的session数据进行销毁操作下面这个函数就是实现了这个功能
我们知道Web应用中有用户退出这个操作那么当用户退出应用的时候我们需要对该用户的session数据进行销毁操作上面的代码已经演示了如何使用session重置操作下面这个函数就是实现了这个功能:
//Destroy sessionid
func (this *SessionManager) SessionDestroy(w ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(this.cookieName)
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request){
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
return
} else {
this.lock.Lock()
defer this.lock.Unlock()
this.provider.SessionDestroy(cookie.Value)
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionDestroy(cookie.Value)
expiration := time.Now()
cookie := http.Cookie{Name: this.cookieName, Expires: expiration}
cookie := http.Cookie{Name: manager.cookieName, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1}
http.SetCookie(w, &cookie)
}
}
@@ -198,14 +194,14 @@ SessionStart函数返回的是一个满足Session接口的变量那么我们
我们来看一下Session管理器如何来管理销毁,只要我们在Main启动的时候启动
func init() {
globalSessions.GC()
go globalSessions.GC()
}
func (this *SessionManager) GC() {
this.lock.Lock()
defer this.lock.Unlock()
this.provider.GC(this.maxLifeTime)
time.AfterFunc(this.maxLifeTime, func() { this.GC() })
func (manager *Manager) GC() {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionGC(manager.maxlifetime)
time.AfterFunc(time.Duration(manager.maxlifetime), func() { manager.GC() })
}
我们可以看到GC充分利用了time包中的定时器功能当超时`maxLifeTime`之后调用GC函数这样就可以保证`maxLifeTime`时间内的session都是可用的类似的方案也可以用于统计在线用户数之类的。

131
6.3.md
View File

@@ -4,12 +4,13 @@
package memory
import (
"github.com/astaxie/session/"
"time"
"container/list"
"github.com/astaxie/session"
"sync"
"time"
)
var d = &Provider{list:list.New()}
var pder = &Provider{list: list.New()}
type SessionStore struct {
sid string //session id唯一标示
@@ -17,104 +18,118 @@
value map[interface{}]interface{} //session里面存储的值
}
func (this *SessionStore) Set(key, value interface{}) bool {
this.value[key] = value
d.SessionUpdate(this.sid)
return true
func (st *SessionStore) Set(key, value interface{}) error {
st.value[key] = value
pder.SessionUpdate(st.sid)
return nil
}
func (this *SessionStore) Get(key interface{}) interface{} {
d.SessionUpdate(this.sid)
if v, ok := this.value[key]; ok {
func (st *SessionStore) Get(key interface{}) interface{} {
pder.SessionUpdate(st.sid)
if v, ok := st.value[key]; ok {
return v
} else {
return ""
return nil
}
return nil
}
func (this *SessionStore) Del(key interface{}) bool {
delete(this.value, key)
d.SessionUpdate(this.sid)
return true
func (st *SessionStore) Delete(key interface{}) error {
delete(st.value, key)
pder.SessionUpdate(st.sid)
return nil
}
func (st *SessionStore) SessionID() string {
return st.sid
}
type Provider struct {
lock sync.Mutex //用来锁
sessions map[string]*SessionStore //用来存储在内存
sessions map[string]*list.Element //用来存储在内存
list *list.List //用来做gc
}
func (this *Provider) SessionInit(sid string) (session.Session, error) {
this.lock.Lock()
defer this.lock.Unlock()
func (pder *Provider) SessionInit(sid string) (session.Session, error) {
pder.lock.Lock()
defer pder.lock.Unlock()
v := make(map[interface{}]interface{}, 0)
newsess := &SessionStore{"sid": sid, "timeAccessed": time.Now(), "value": v}
this.sessions[sid] = newsess
this.list.Push(newsess)
return newsess
newsess := &SessionStore{sid: sid, timeAccessed: time.Now(), value: v}
element := pder.list.PushBack(newsess)
pder.sessions[sid] = element
return newsess, nil
}
func (this *Provider) SessionRead(sid string) (session.Session, error) {
if s, ok := this.sessions[sid]; ok {
return s, nil
func (pder *Provider) SessionRead(sid string) (session.Session, error) {
if element, ok := pder.sessions[sid]; ok {
return element.Value.(*SessionStore), nil
} else {
sess, err := this.SessionInit(sid)
sess, err := pder.SessionInit(sid)
return sess, err
}
return nil, nil
}
func (this *Provider) SessionDestroy(sid string) bool {
if s, ok := this.sessions[sid]; ok {
delete(this.table, sid)
this.list.Remove(s)
return true
} else {
return false
func (pder *Provider) SessionDestroy(sid string) error {
if element, ok := pder.sessions[sid]; ok {
delete(pder.sessions, sid)
pder.list.Remove(element)
return nil
}
return nil
}
func (this *Provider) SessionGC(maxlifetime int64) {
this.lock.Lock()
defer this.lock.Unlock()
func (pder *Provider) SessionGC(maxlifetime int64) {
pder.lock.Lock()
defer pder.lock.Unlock()
for {
element := this.list.Back()
element := pder.list.Back()
if element == nil {
break
}
if (element.Value.(*SessionStore).timeAccessed.Unix() + maxlifetime) < time.Now().Unix() {
this.list.Remove(element)
delete(this.table, element.Value.(*SessionStore).sid)
pder.list.Remove(element)
delete(pder.sessions, element.Value.(*SessionStore).sid)
} else {
break
}
}
}
func (this *Provider) SessionUpdate(sid string) bool {
this.lock.Lock()
defer this.lock.Unlock()
if element, ok := this.sessions[sid]; ok {
element.Value.(*SessionStore).value = s.value
this.moveToFront(element)
return true
} else {
return false
func (pder *Provider) SessionUpdate(sid string) error {
pder.lock.Lock()
defer pder.lock.Unlock()
if element, ok := pder.sessions[sid]; ok {
element.Value.(*SessionStore).timeAccessed = time.Now()
pder.list.MoveToFront(element)
return nil
}
}
func (this *Provider) moveToFront(element *list.Element) {
this.lock.Lock()
defer this.lock.Unlock()
element.Value.(*SessionStore).timeAccessed = time.Now()
this.list.MoveToFront(element)
return nil
}
func init() {
session.Register("memory", d)
pder.sessions = make(map[string]*list.Element, 0)
session.Register("memory", pder)
}
上面这个代码实现了一个内存存储的session机制。通过init函数注册到session管理器中。这样就可以方便的调用了。我们如何来调用该引擎呢请看下面的代码
import (
"github.com/astaxie/session"
_ "github.com/astaxie/session/providers/memory"
)
当import的时候已经执行了memory函数里面的init函数这样就已经注册到session管理器中我们就可以使用了通过如下方式就可以初始化一个session管理器
var globalSessions *session.Manager
//然后在init函数中初始化
func init() {
globalSessions, _ = session.NewManager("memory", "gosessionid", 3600)
go globalSessions.GC()
}
上面这个代码实现了一个内存存储的session机制。通过init函数注册到session管理器中。这样就可以方便的调用了。
## links
* [目录](<preface.md>)

2
6.4.md
View File

@@ -57,7 +57,7 @@ count.gtpl的代码如下所示
if createtime == nil {
sess.Set("createtime", time.Now().Unix())
} else if (createtime.(int64) + 60) < (time.Now().Unix()) {
globalSessions.SessionDestroy(sess.SessionID())
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}