conf.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // NewRedis returns a Redis.
  28. // Deprecated: use MustNewRedis or NewRedis instead.
  29. func (rc RedisConf) NewRedis() *Redis {
  30. var opts []Option
  31. if rc.Type == ClusterType {
  32. opts = append(opts, Cluster())
  33. }
  34. if len(rc.Pass) > 0 {
  35. opts = append(opts, WithPass(rc.Pass))
  36. }
  37. if rc.Tls {
  38. opts = append(opts, WithTLS())
  39. }
  40. return New(rc.Host, opts...)
  41. }
  42. // Validate validates the RedisConf.
  43. func (rc RedisConf) Validate() error {
  44. if len(rc.Host) == 0 {
  45. return ErrEmptyHost
  46. }
  47. if len(rc.Type) == 0 {
  48. return ErrEmptyType
  49. }
  50. return nil
  51. }
  52. // Validate validates the RedisKeyConf.
  53. func (rkc RedisKeyConf) Validate() error {
  54. if err := rkc.RedisConf.Validate(); err != nil {
  55. return err
  56. }
  57. if len(rkc.Key) == 0 {
  58. return ErrEmptyKey
  59. }
  60. return nil
  61. }