cache.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package cache
  2. import (
  3. "encoding/json"
  4. )
  5. type Handler interface {
  6. Get(key string, value interface{}) error
  7. Set(key string, value interface{}, exp int) error
  8. Gc() error
  9. }
  10. // MaxTimeOut 最大超时时间
  11. const (
  12. TypeMem = "memory"
  13. TypeRedis = "redis"
  14. TypeFile = "file"
  15. MaxTimeOut = 365 * 24 * 3600
  16. )
  17. func New(typ string) Handler {
  18. var cache Handler
  19. switch typ {
  20. case TypeFile:
  21. cache = NewFileCache()
  22. case TypeRedis:
  23. cache = new(RedisCache)
  24. case TypeMem: // memory
  25. cache = NewMemoryCache(0)
  26. default:
  27. cache = NewMemoryCache(0)
  28. }
  29. return cache
  30. }
  31. func EncodeValue(value interface{}) (string, error) {
  32. /*if v, ok := value.(string); ok {
  33. return v, nil
  34. }
  35. if v, ok := value.([]byte); ok {
  36. return string(v), nil
  37. }*/
  38. b, err := json.Marshal(value)
  39. if err != nil {
  40. return "", err
  41. }
  42. return string(b), nil
  43. }
  44. func DecodeValue(value string, rtv interface{}) error {
  45. //判断rtv的类型是否是string,如果是string,直接赋值并返回
  46. /*switch rtv.(type) {
  47. case *string:
  48. *(rtv.(*string)) = value
  49. return nil
  50. case *[]byte:
  51. *(rtv.(*[]byte)) = []byte(value)
  52. return nil
  53. //struct
  54. case *interface{}:
  55. err := json.Unmarshal(([]byte)(value), rtv)
  56. return err
  57. default:
  58. err := json.Unmarshal(([]byte)(value), rtv)
  59. return err
  60. }
  61. */
  62. err := json.Unmarshal(([]byte)(value), rtv)
  63. return err
  64. }