github.com/lingyao2333/mo-zero@v1.4.1/core/stores/redis/conf.go (about)

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