lifetime.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package sessions
  2. import (
  3. "time"
  4. )
  5. // LifeTime controls the session expiration datetime.
  6. type LifeTime struct {
  7. // Remember, tip for the future:
  8. // No need of gob.Register, because we embed the time.Time.
  9. // And serious bug which has a result of me spending my whole evening:
  10. // Because of gob encoding it doesn't encodes/decodes the other fields if time.Time is embedded
  11. // (this should be a bug(go1.9-rc1) or not. We don't care atm)
  12. time.Time
  13. timer *time.Timer
  14. }
  15. // Begin will begin the life based on the time.Now().Add(d).
  16. // Use `Continue` to continue from a stored time(database-based session does that).
  17. func (lt *LifeTime) Begin(d time.Duration, onExpire func()) {
  18. if d <= 0 {
  19. return
  20. }
  21. lt.Time = time.Now().Add(d)
  22. lt.timer = time.AfterFunc(d, onExpire)
  23. }
  24. // Revive will continue the life based on the stored Time.
  25. // Other words that could be used for this func are: Continue, Restore, Resc.
  26. func (lt *LifeTime) Revive(onExpire func()) {
  27. if lt.Time.IsZero() {
  28. return
  29. }
  30. now := time.Now()
  31. if lt.Time.After(now) {
  32. d := lt.Time.Sub(now)
  33. lt.timer = time.AfterFunc(d, onExpire)
  34. }
  35. }
  36. // Shift resets the lifetime based on "d".
  37. func (lt *LifeTime) Shift(d time.Duration) {
  38. if d > 0 && lt.timer != nil {
  39. lt.Time = time.Now().Add(d)
  40. lt.timer.Reset(d)
  41. }
  42. }
  43. // ExpireNow reduce the lifetime completely.
  44. func (lt *LifeTime) ExpireNow() {
  45. lt.Time = CookieExpireDelete
  46. if lt.timer != nil {
  47. lt.timer.Stop()
  48. }
  49. }
  50. // HasExpired reports whether "lt" represents is expired.
  51. func (lt *LifeTime) HasExpired() bool {
  52. if lt.IsZero() {
  53. return false
  54. }
  55. return lt.Time.Before(time.Now())
  56. }
  57. // DurationUntilExpiration returns the duration until expires, it can return negative number if expired,
  58. // a call to `HasExpired` may be useful before calling this `Dur` function.
  59. func (lt *LifeTime) DurationUntilExpiration() time.Duration {
  60. return time.Until(lt.Time)
  61. }