diff --git a/main.go b/main.go index 9efef3e..f5f73d4 100644 --- a/main.go +++ b/main.go @@ -40,7 +40,7 @@ func init() { // Wide 首页. func indexHandler(w http.ResponseWriter, r *http.Request) { // 创建一个 Wide 会话 - wideSession := user.NewSession() + wideSession := user.WideSessions.New() i18n.Load() @@ -54,7 +54,8 @@ func indexHandler(w http.ResponseWriter, r *http.Request) { name := conf.Wide.Users[0].Name httpSession.Values["username"] = name - httpSession.Values["id"] = strconv.Itoa(rand.Int()) + httpSessionId := strconv.Itoa(rand.Int()) + httpSession.Values["id"] = httpSessionId // 一天过期 httpSession.Options.MaxAge = 60 * 60 * 24 @@ -63,6 +64,9 @@ func indexHandler(w http.ResponseWriter, r *http.Request) { httpSession.Save(r, w) + // Wide 会话关联 HTTP 会话 + wideSession.HTTPSessionId = httpSession.Values["id"].(string) + t, err := template.ParseFiles("view/index.html") if nil != err { diff --git a/user/sessions.go b/user/sessions.go index 162596e..559be74 100644 --- a/user/sessions.go +++ b/user/sessions.go @@ -5,6 +5,7 @@ import ( "strconv" "time" + "github.com/golang/glog" "github.com/gorilla/sessions" ) @@ -17,23 +18,55 @@ var Session = sessions.NewCookieStore([]byte("BEYOND")) // Wide 会话,对应一个浏览器 tab. type WideSession struct { - Id string // 唯一标识 - State int // 状态 - Created time.Time // 创建时间 - Updated time.Time // 最近一次使用时间 + Id string // 唯一标识 + HTTPSessionId string // HTTP 会话 id + State int // 状态 + Created time.Time // 创建时间 + Updated time.Time // 最近一次使用时间 } +type Sessions []*WideSession + +// 所有 Wide 会话集. +var WideSessions Sessions + // 创建一个 Wide 会话. -func NewSession() *WideSession { +func (sessions *Sessions) New() *WideSession { rand.Seed(time.Now().UnixNano()) id := strconv.Itoa(rand.Int()) now := time.Now() - return &WideSession{ + ret := &WideSession{ Id: id, State: SessionStateActive, Created: now, Updated: now, } + + *sessions = append(*sessions, ret) + + return ret +} + +// 移除 Wide 会话. +func (sessions *Sessions) Remove(sid string) { + for i, s := range *sessions { + if s.Id == sid { + *sessions = append((*sessions)[:i], (*sessions)[i+1:]...) + + glog.V(3).Infof("Has [%d] wide sessions currently", len(*sessions)) + } + } +} + +// 移除 HTTP 会话关联的所有 Wide 会话. +func (sessions *Sessions) RemoveByHTTPSid(httpSessionId string) { + for i, s := range *sessions { + if s.HTTPSessionId == httpSessionId { + *sessions = append((*sessions)[:i], (*sessions)[i+1:]...) + + glog.V(3).Infof("Has [%d] wide sessions currently", len(*sessions)) + } + } } diff --git a/view/index.html b/view/index.html index 4a70580..2b671c6 100644 --- a/view/index.html +++ b/view/index.html @@ -2,7 +2,7 @@ - {{.i18n.wide}} - {{.session.Id}} + {{.i18n.wide}} @@ -167,10 +167,11 @@