main.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package session
  2. import (
  3. "errors"
  4. "gogs.qqck.cn/s/gotools/randex"
  5. "sync"
  6. "time"
  7. )
  8. var err_nil = errors.New("session 无效")
  9. type Sessiong struct {
  10. //并发锁
  11. lock sync.Mutex
  12. //哈希表
  13. hash map[string]*item
  14. time_life int64 // session有效时长,单位:秒
  15. }
  16. type item struct {
  17. time int64 // 最后访问时间,单位:秒
  18. val any
  19. }
  20. func New() (t *Sessiong) {
  21. t = new(Sessiong)
  22. t.hash = make(map[string]*item)
  23. t.time_life = 60 * 60 * 24
  24. return
  25. }
  26. // SetTimeLife 设置session过期时间,默认为:24h
  27. // life session有效时长,单位:秒
  28. func (t *Sessiong) SetTimeLife(life int64) *Sessiong {
  29. if life < 1 {
  30. life = 60 * 60 * 24
  31. }
  32. t.lock.Lock()
  33. defer t.lock.Unlock()
  34. t.time_life = life
  35. return t
  36. }
  37. //-----------------------------------------------------------------------------------------------------API
  38. func (t *Sessiong) Create(val any) (session string) {
  39. t.lock.Lock()
  40. defer t.lock.Unlock()
  41. for {
  42. session = randex.Str0aZ(64)
  43. if _, j_is := t.hash[session]; !j_is {
  44. break
  45. }
  46. }
  47. t.hash[session] = &item{
  48. time: time.Now().Unix(),
  49. val: val,
  50. }
  51. return
  52. }
  53. func (t *Sessiong) Set(session string, val any) *Sessiong {
  54. t.lock.Lock()
  55. defer t.lock.Unlock()
  56. if _, j_is := t.hash[session]; !j_is {
  57. return t
  58. }
  59. t.hash[session].time = time.Now().Unix()
  60. t.hash[session].val = val
  61. return t
  62. }
  63. func (t *Sessiong) Get(session string) (any, error) {
  64. t.lock.Lock()
  65. defer t.lock.Unlock()
  66. if _, j_is := t.hash[session]; !j_is {
  67. return nil, err_nil
  68. }
  69. j_time := time.Now().Unix()
  70. if j_time-t.hash[session].time > t.time_life {
  71. delete(t.hash, session)
  72. return nil, err_nil
  73. }
  74. t.hash[session].time = j_time
  75. return t.hash[session].val, nil
  76. }
  77. // Delete 删除指定键
  78. func (t *Sessiong) Delete(session string) {
  79. t.lock.Lock()
  80. defer t.lock.Unlock()
  81. delete(t.hash, session)
  82. }
  83. // Clean 清除过期的session
  84. func (t *Sessiong) Clean() {
  85. t.lock.Lock()
  86. defer t.lock.Unlock()
  87. j_time := time.Now().Unix()
  88. for j_session, j_item := range t.hash {
  89. if j_time-j_item.time > t.time_life {
  90. delete(t.hash, j_session)
  91. }
  92. }
  93. }