web_session.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package main
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "net/http"
  6. "sync"
  7. "time"
  8. )
  9. type sessionInfo struct {
  10. last time.Time
  11. }
  12. var (
  13. sessionMu sync.Mutex
  14. sessions = make(map[string]*sessionInfo)
  15. )
  16. // 默认5分钟无任何页面点击操作时, 超时
  17. const idleTimeout = 5 * time.Minute
  18. func createSession() string {
  19. buf := make([]byte, 32)
  20. rand.Read(buf)
  21. return hex.EncodeToString(buf)
  22. }
  23. func addSession(id string) {
  24. sessionMu.Lock()
  25. sessions[id] = &sessionInfo{last: time.Now()}
  26. sessionMu.Unlock()
  27. }
  28. func hasSession(id string) bool {
  29. now := time.Now()
  30. sessionMu.Lock()
  31. defer sessionMu.Unlock()
  32. s, ok := sessions[id]
  33. if !ok {
  34. return false
  35. }
  36. if now.Sub(s.last) > idleTimeout {
  37. delete(sessions, id)
  38. return false
  39. }
  40. s.last = now
  41. return true
  42. }
  43. func checkSession(r *http.Request) bool {
  44. c, err := r.Cookie("session_id")
  45. if err != nil {
  46. return false
  47. }
  48. return hasSession(c.Value)
  49. }
  50. func sessionCleaner() {
  51. ticker := time.NewTicker(3 * time.Minute)
  52. defer ticker.Stop()
  53. for range ticker.C {
  54. now := time.Now()
  55. sessionMu.Lock()
  56. for k, s := range sessions {
  57. if now.Sub(s.last) > idleTimeout {
  58. delete(sessions, k)
  59. }
  60. }
  61. sessionMu.Unlock()
  62. }
  63. }