cache.go 772 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package permlib
  2. import (
  3. "sync"
  4. "time"
  5. "golang.org/x/sync/singleflight"
  6. )
  7. type cachedUser struct {
  8. UserId int64
  9. Username string
  10. ProductCode string
  11. MemberType string
  12. Perms []string
  13. expiresAt time.Time
  14. }
  15. type permCache struct {
  16. store sync.Map
  17. ttl time.Duration
  18. sf singleflight.Group
  19. }
  20. func newPermCache(ttl time.Duration) *permCache {
  21. return &permCache{ttl: ttl}
  22. }
  23. func (c *permCache) get(key string) (*cachedUser, bool) {
  24. v, ok := c.store.Load(key)
  25. if !ok {
  26. return nil, false
  27. }
  28. entry := v.(*cachedUser)
  29. if time.Now().After(entry.expiresAt) {
  30. c.store.Delete(key)
  31. return nil, false
  32. }
  33. return entry, true
  34. }
  35. func (c *permCache) set(key string, u *cachedUser) {
  36. u.expiresAt = time.Now().Add(c.ttl)
  37. c.store.Store(key, u)
  38. }