@@ -33,35 +33,35 @@ session的基本原理是由服务器为每个会话维护一份信息数据,
3333
3434定义一个全局的session管理器
3535
36- type SessionManager struct {
36+ type Manager struct {
3737 cookieName string //private cookiename
3838 lock sync.Mutex // protects session
3939 provider Provider
40- maxLifeTime int64
40+ maxlifetime int64
4141 }
4242
43- func NewSessionManager (provideName, cookieName string, maxLifeTime int64) (*SessionManager , error) {
43+ func NewManager (provideName, cookieName string, maxlifetime int64) (*Manager , error) {
4444 provider, ok := provides[provideName]
4545 if !ok {
4646 return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
4747 }
48- return &SessionManager {provider: provider, cookieName: cookieName, maxLifeTime: maxLifeTime }, nil
49- }
48+ return &Manager {provider: provider, cookieName: cookieName, maxlifetime: maxlifetime }, nil
49+ }
5050
5151Go实现整个的流程应该也是这样的,在main包中创建一个全部的session管理器
5252
53- var globalSessions *SessionManager
53+ var globalSessions *session.Manager
5454 //然后在init函数中初始化
5555 func init() {
56- globalSessions = NewSessionManager ("memory","gosessionid",3600)
56+ globalSessions = NewManager ("memory","gosessionid",3600)
5757 }
5858
5959我们知道session是保存在服务器端的数据,它可以以任何的方式存储,比如存储在内存、数据库或者文件中。因此我们抽象出一个Provider接口,用以表征session管理器底层存储结构。
6060
6161 type Provider interface {
6262 SessionInit(sid string) (Session, error)
6363 SessionRead(sid string) (Session, error)
64- SessionDestroy(sid string) bool
64+ SessionDestroy(sid string) error
6565 SessionGC(maxLifeTime int64)
6666 }
6767
@@ -70,12 +70,13 @@ Go实现整个的流程应该也是这样的,在main包中创建一个全部
7070- SessionDestroy函数用来销毁sid对应的Session变量
7171- SessionGC根据maxLifeTime来删除过期的数据
7272
73- 那么Session接口需要实现什么样的功能呢?有过Web开发经验的读者知道,对Session的处理基本就 设置值、读取值、删除值这三个操作,所以我们的Session接口也就实现这三个操作 。
73+ 那么Session接口需要实现什么样的功能呢?有过Web开发经验的读者知道,对Session的处理基本就 设置值、读取值、删除值以及获取当前sessionID这四个操作,所以我们的Session接口也就实现这四个操作 。
7474
7575 type Session interface {
76- Set(key interface{}, value interface{}) //set session value
77- Get(key interface{}) interface{} //get session value
78- Del(key interface{}) bool //delete session value
76+ Set(key, value interface{}) error //set session value
77+ Get(key interface{}) interface{} //get session value
78+ Delete(key interface{}) error //delete session value
79+ SessionID() string //back current sessionID
7980 }
8081
8182> 以上设计思路来源于database/sql/driver,先定义好接口,然后具体的存储session的结构实现相应的接口并注册后,相应功能这样就可以使用了,以下是用来随需注册存储session的结构的Register函数的实现。
@@ -99,50 +100,45 @@ Go实现整个的流程应该也是这样的,在main包中创建一个全部
99100
100101Session ID是用来识别访问Web应用的每一个用户,因此必须保证它是全局唯一的(GUID),下面代码展示了如何满足这一需求:
101102
102- func (this *SessionManager ) sessionId() string {
103+ func (manager *Manager ) sessionId() string {
103104 b := make([]byte, 32)
104105 if _, err := io.ReadFull(rand.Reader, b); err != nil {
105106 return ""
106107 }
107- return string (b)
108+ return base64.URLEncoding.EncodeToString (b)
108109 }
109110
110111###session创建
111112我们需要为每个来访用户分配或获取与他相关连的Session,以便后面根据Session信息来验证操作。SessionStart这个函数就是用来检测是否已经有某个Session与当前来访用户发生了关联,如果没有则创建之。
112113
113- func (this *SessionManager ) SessionStart(w ResponseWriter, r *http.Request) (session Session) {
114- this .lock.Lock()
115- defer this .lock.Unlock()
116- cookie, err := r.Cookie(this .cookieName)
114+ func (manager *Manager ) SessionStart(w http. ResponseWriter, r *http.Request) (session Session) {
115+ manager .lock.Lock()
116+ defer manager .lock.Unlock()
117+ cookie, err := r.Cookie(manager .cookieName)
117118 if err != nil || cookie.Value == "" {
118- sid := this.sessionId()
119- session = this.provider.SessionInit(sid)
120- expiration := time.Now()
121- expiration.Add(time.Duration(this.maxlifetime))
122- cookie := http.Cookie{Name: this.cookieName, Value: sid, Expires: expiration}
119+ sid := manager.sessionId()
120+ session, _ = manager.provider.SessionInit(sid)
121+ cookie := http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxlifetime)}
123122 http.SetCookie(w, &cookie)
124123 } else {
125- session = this.provider.SessionRead(cookie.Value)
124+ sid, _ := url.QueryUnescape(cookie.Value)
125+ session, _ = manager.provider.SessionRead(sid)
126126 }
127127 return
128128 }
129129
130130我们用前面login操作来演示session的运用:
131131
132132 func login(w http.ResponseWriter, r *http.Request) {
133- session:= globalSessions.SessionStart(w,r)
134- fmt.Println("method:", r.Method) //获取请求的方法
133+ sess := globalSessions.SessionStart(w, r)
134+ r.ParseForm()
135135 if r.Method == "GET" {
136- if session.Get("uid").(string) != "" {
137- t, _ := template.ParseFiles("main.gtpl")
138- }else{
139- t, _ := template.ParseFiles("login.gtpl")
140- }
141- t.Execute(w, nil)
136+ t, _ := template.ParseFiles("login.gtpl")
137+ w.Header().Set("Content-Type", "text/html")
138+ t.Execute(w, sess.Get("username"))
142139 } else {
143- //请求的是登陆数据,那么执行登陆的逻辑判断
144- fmt.Println("username:", r.Form["username"])
145- fmt.Println("password:", r.Form["password"])
140+ sess.Set("username", r.Form["username"])
141+ http.Redirect(w, r, "/", 302)
146142 }
147143 }
148144
@@ -151,44 +147,44 @@ SessionStart函数返回的是一个满足Session接口的变量,那么我们
151147
152148上面的例子中的代码` session.Get("uid") ` 已经展示了基本的读取数据的操作,现在我们再来看一下详细的操作:
153149
154- func login(w http.ResponseWriter, r *http.Request) {
155- session:=globalSessions.SessionStart(w,r)
156- fmt.Println("method:", r.Method) //获取请求的方法
157- if r.Method == "GET" {
158- if session.Get("uid").(string) != "" {
159- session.Del("password")
160- t, _ := template.ParseFiles("main.gtpl")
161- }else{
162- t, _ := template.ParseFiles("login.gtpl")
163- }
164- t.Execute(w, nil)
150+ func count(w http.ResponseWriter, r *http.Request) {
151+ sess := globalSessions.SessionStart(w, r)
152+ createtime := sess.Get("createtime")
153+ if createtime == nil {
154+ sess.Set("createtime", time.Now().Unix())
155+ } else if (createtime.(int64) + 360) < (time.Now().Unix()) {
156+ globalSessions.SessionDestroy(w, r)
157+ sess = globalSessions.SessionStart(w, r)
158+ }
159+ ct := sess.Get("countnum")
160+ if ct == nil {
161+ sess.Set("countnum", 1)
165162 } else {
166- //请求的是登陆数据,那么执行登陆的逻辑判断
167- fmt.Println("username:", r.Form["username"])
168- fmt.Println("password:", r.Form["password"])
169- session.Set("username",r.Form["username"])
170- session.Set("password",r.Form["password"])
163+ sess.Set("countnum", (ct.(int) + 1))
171164 }
172- }
165+ t, _ := template.ParseFiles("count.gtpl")
166+ w.Header().Set("Content-Type", "text/html")
167+ t.Execute(w, sess.Get("countnum"))
168+ }
173169
174- 通过上面的例子可以看到,Session的操作和操作key/value数据库类似: Set 、Get、Del等操作
170+ 通过上面的例子可以看到,Session的操作和操作key/value数据库类似: Set 、Get、Delete等操作
175171
176172因为Session有过期的概念,所以我们定义了GC操作,当访问过期时间满足GC的触发条件后将会引起GC,但是当我们进行了任意一个session操作,都会对Session实体进行更新,都会触发对最后访问时间的修改,这样当GC的时候就不会误删除还在使用的Session实体。
177173
178174###session重置
179- 我们知道,Web应用中有用户退出这个操作,那么当用户退出应用的时候,我们需要对该用户的session数据进行销毁操作,下面这个函数就是实现了这个功能:
175+ 我们知道,Web应用中有用户退出这个操作,那么当用户退出应用的时候,我们需要对该用户的session数据进行销毁操作,上面的代码已经演示了如何使用session重置操作, 下面这个函数就是实现了这个功能:
180176
181177 //Destroy sessionid
182- func (this *SessionManager ) SessionDestroy(w ResponseWriter, r *http.Request) {
183- cookie, err := r.Cookie(this .cookieName)
178+ func (manager *Manager ) SessionDestroy(w http. ResponseWriter, r *http.Request){
179+ cookie, err := r.Cookie(manager .cookieName)
184180 if err != nil || cookie.Value == "" {
185181 return
186182 } else {
187- this .lock.Lock()
188- defer this .lock.Unlock()
189- this .provider.SessionDestroy(cookie.Value)
183+ manager .lock.Lock()
184+ defer manager .lock.Unlock()
185+ manager .provider.SessionDestroy(cookie.Value)
190186 expiration := time.Now()
191- cookie := http.Cookie{Name: this .cookieName, Expires: expiration}
187+ cookie := http.Cookie{Name: manager .cookieName, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1 }
192188 http.SetCookie(w, &cookie)
193189 }
194190 }
@@ -198,14 +194,14 @@ SessionStart函数返回的是一个满足Session接口的变量,那么我们
198194我们来看一下Session管理器如何来管理销毁,只要我们在Main启动的时候启动:
199195
200196 func init() {
201- globalSessions.GC()
197+ go globalSessions.GC()
202198 }
203199
204- func (this *SessionManager ) GC() {
205- this .lock.Lock()
206- defer this .lock.Unlock()
207- this .provider.GC(this.maxLifeTime )
208- time.AfterFunc(this.maxLifeTime , func() { this .GC() })
200+ func (manager *Manager ) GC() {
201+ manager .lock.Lock()
202+ defer manager .lock.Unlock()
203+ manager .provider.SessionGC(manager.maxlifetime )
204+ time.AfterFunc(time.Duration(manager.maxlifetime) , func() { manager .GC() })
209205 }
210206
211207我们可以看到GC充分利用了time包中的定时器功能,当超时` maxLifeTime ` 之后调用GC函数,这样就可以保证` maxLifeTime ` 时间内的session都是可用的,类似的方案也可以用于统计在线用户数之类的。
0 commit comments