conf.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. )
  11. type (
  12. // A RedisConf is a redis config.
  13. RedisConf struct {
  14. Host string
  15. Type string `json:",default=node,options=node|cluster"`
  16. Pass string `json:",optional"`
  17. Tls bool `json:",default=false,options=true|false"`
  18. }
  19. // A RedisKeyConf is a redis config with key.
  20. RedisKeyConf struct {
  21. RedisConf
  22. Key string `json:",optional"`
  23. }
  24. )
  25. // NewRedis returns a Redis.
  26. func (rc RedisConf) NewRedis() *Redis {
  27. var opts []Option
  28. if rc.Type == ClusterType {
  29. opts = append(opts, Cluster())
  30. }
  31. if len(rc.Pass) > 0 {
  32. opts = append(opts, WithPass(rc.Pass))
  33. }
  34. if rc.Tls {
  35. opts = append(opts, WithTLS())
  36. }
  37. return New(rc.Host, opts...)
  38. }
  39. // Validate validates the RedisConf.
  40. func (rc RedisConf) Validate() error {
  41. if len(rc.Host) == 0 {
  42. return ErrEmptyHost
  43. }
  44. if len(rc.Type) == 0 {
  45. return ErrEmptyType
  46. }
  47. return nil
  48. }
  49. // Validate validates the RedisKeyConf.
  50. func (rkc RedisKeyConf) Validate() error {
  51. if err := rkc.RedisConf.Validate(); err != nil {
  52. return err
  53. }
  54. if len(rkc.Key) == 0 {
  55. return ErrEmptyKey
  56. }
  57. return nil
  58. }