| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package main
- import (
- "crypto/rand"
- "encoding/hex"
- "net/http"
- "sync"
- "time"
- )
- type sessionInfo struct {
- last time.Time
- }
- var (
- sessionMu sync.Mutex
- sessions = make(map[string]*sessionInfo)
- )
- // 默认5分钟无任何页面点击操作时, 超时
- const idleTimeout = 5 * time.Minute
- func createSession() string {
- buf := make([]byte, 32)
- rand.Read(buf)
- return hex.EncodeToString(buf)
- }
- func addSession(id string) {
- sessionMu.Lock()
- sessions[id] = &sessionInfo{last: time.Now()}
- sessionMu.Unlock()
- }
- func hasSession(id string) bool {
- now := time.Now()
- sessionMu.Lock()
- defer sessionMu.Unlock()
- s, ok := sessions[id]
- if !ok {
- return false
- }
- if now.Sub(s.last) > idleTimeout {
- delete(sessions, id)
- return false
- }
- s.last = now
- return true
- }
- func checkSession(r *http.Request) bool {
- c, err := r.Cookie("session_id")
- if err != nil {
- return false
- }
- return hasSession(c.Value)
- }
- func sessionCleaner() {
- ticker := time.NewTicker(3 * time.Minute)
- defer ticker.Stop()
- for range ticker.C {
- now := time.Now()
- sessionMu.Lock()
- for k, s := range sessions {
- if now.Sub(s.last) > idleTimeout {
- delete(sessions, k)
- }
- }
- sessionMu.Unlock()
- }
- }
|