cached.go 589 B

12345678910111213141516171819202122232425262728293031
  1. /*
  2. * This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  5. */
  6. package main
  7. import "time"
  8. func NewCached[T any](
  9. value *T,
  10. lifetime time.Duration,
  11. ) Cached[T] {
  12. return Cached[T]{
  13. value: value,
  14. expiry: time.Now().UTC().Add(lifetime),
  15. }
  16. }
  17. type Cached[T any] struct {
  18. value *T
  19. expiry time.Time
  20. }
  21. func (c *Cached[T]) Value() *T {
  22. return c.value
  23. }
  24. func (c *Cached[T]) Expired() bool {
  25. return c.expiry.Before(time.Now().UTC())
  26. }