cache.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package feishu
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "time"
  20. )
  21. type IExpirable interface {
  22. CreatedAt() int64
  23. ExpiresIn() int64
  24. }
  25. type ICache interface {
  26. Set(data IExpirable) error
  27. Get(data IExpirable) error
  28. }
  29. type FileCache struct {
  30. Path string
  31. }
  32. func NewFileCache(path string) *FileCache {
  33. return &FileCache{
  34. Path: path,
  35. }
  36. }
  37. func (c *FileCache) Set(data IExpirable) error {
  38. bytes, err := json.Marshal(data)
  39. if err == nil {
  40. ioutil.WriteFile(c.Path, bytes, 0644)
  41. }
  42. return err
  43. }
  44. func (c *FileCache) Get(data IExpirable) error {
  45. bytes, err := ioutil.ReadFile(c.Path)
  46. if err != nil {
  47. return err
  48. }
  49. err = json.Unmarshal(bytes, data)
  50. if err != nil {
  51. return err
  52. }
  53. created := data.CreatedAt()
  54. expires := data.ExpiresIn()
  55. // The operator '-120' can give us a head start on the expiration date
  56. if time.Now().Unix() > created+expires-120 {
  57. err = fmt.Errorf("Data is already expired")
  58. }
  59. return err
  60. }