conf.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package redis
  2. import "errors"
  3. var (
  4. // ErrEmptyHost is an error that indicates no redis host is set.
  5. ErrEmptyHost = errors.New("empty redis host")
  6. // ErrEmptyType is an error that indicates no redis type is set.
  7. ErrEmptyType = errors.New("empty redis type")
  8. // ErrEmptyKey is an error that indicates no redis key is set.
  9. ErrEmptyKey = errors.New("empty redis key")
  10. // ErrPing is an error that indicates ping failed.
  11. ErrPing = errors.New("ping redis failed")
  12. )
  13. type (
  14. // A RedisConf is a redis config.
  15. RedisConf struct {
  16. Host string
  17. Type string `json:",default=node,options=node|cluster"`
  18. Pass string `json:",optional"`
  19. Tls bool `json:",optional"`
  20. }
  21. // A RedisKeyConf is a redis config with key.
  22. RedisKeyConf struct {
  23. RedisConf
  24. Key string `json:",optional"`
  25. }
  26. )
  27. // Deprecated: use MustNewRedis or NewRedis instead.
  28. func (rc RedisConf) NewRedis() *Redis {
  29. var opts []Option
  30. if rc.Type == ClusterType {
  31. opts = append(opts, Cluster())
  32. }
  33. if len(rc.Pass) > 0 {
  34. opts = append(opts, WithPass(rc.Pass))
  35. }
  36. if rc.Tls {
  37. opts = append(opts, WithTLS())
  38. }
  39. return New(rc.Host, opts...)
  40. }
  41. // Validate validates the RedisConf.
  42. func (rc RedisConf) Validate() error {
  43. if len(rc.Host) == 0 {
  44. return ErrEmptyHost
  45. }
  46. if len(rc.Type) == 0 {
  47. return ErrEmptyType
  48. }
  49. return nil
  50. }
  51. // Validate validates the RedisKeyConf.
  52. func (rkc RedisKeyConf) Validate() error {
  53. if err := rkc.RedisConf.Validate(); err != nil {
  54. return err
  55. }
  56. if len(rkc.Key) == 0 {
  57. return ErrEmptyKey
  58. }
  59. return nil
  60. }