From 9a17a3f6e5b06c13547f91153672d0eb18e16fc2 Mon Sep 17 00:00:00 2001 From: xiemengjun Date: Thu, 27 Sep 2012 00:06:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=9A=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 6.2.md | 130 +++++++++++++++++++++++++++----------------------------- 6.3.md | 131 ++++++++++++++++++++++++++++++++------------------------- 6.4.md | 2 +- 3 files changed, 137 insertions(+), 126 deletions(-) diff --git a/6.2.md b/6.2.md index 8d317454..0ba53378 100644 --- a/6.2.md +++ b/6.2.md @@ -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都是可用的,类似的方案也可以用于统计在线用户数之类的。 diff --git a/6.3.md b/6.3.md index 1cafb10f..193d9892 100644 --- a/6.3.md +++ b/6.3.md @@ -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 * [目录]() diff --git a/6.4.md b/6.4.md index 4f5bcd77..7afcb6a5 100644 --- a/6.4.md +++ b/6.4.md @@ -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) }