util.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package redis
  4. import (
  5. "fmt"
  6. "github.com/go-redis/redis"
  7. )
  8. type Error string
  9. func (err Error) Error() string { return string(err) }
  10. func sliceHelper(reply interface{}, err error, name string, makeSlice func(int), assign func(int, interface{}) error) error {
  11. if err != nil {
  12. return err
  13. }
  14. switch reply := reply.(type) {
  15. case []interface{}:
  16. makeSlice(len(reply))
  17. for i := range reply {
  18. if reply[i] == nil {
  19. continue
  20. }
  21. if err := assign(i, reply[i]); err != nil {
  22. return err
  23. }
  24. }
  25. return nil
  26. case nil:
  27. return redis.Nil
  28. case Error:
  29. return reply
  30. }
  31. return fmt.Errorf("cache: unexpected type for %s, got type %T", name, reply)
  32. }
  33. func strings(reply interface{}, err error) ([]string, error) {
  34. var result []string
  35. err = sliceHelper(reply, err, "strings",
  36. func(n int) { result = make([]string, n) }, func(i int, v interface{}) error {
  37. switch v := v.(type) {
  38. case string:
  39. result[i] = v
  40. return nil
  41. case []byte:
  42. result[i] = string(v)
  43. return nil
  44. default:
  45. return fmt.Errorf("cache: unexpected element type for strings, got type %T", v)
  46. }
  47. })
  48. if err != nil {
  49. if len(result) <= 0 {
  50. err = redis.Nil
  51. }
  52. }
  53. return result, err
  54. }