Files
mtusi2026lab2/service/internal/config/redis.go
T

65 lines
1.1 KiB
Go

package config
import (
"errors"
"fmt"
"net"
"github.com/redis/go-redis/v9"
"github.com/spf13/viper"
)
type Redis struct {
Host string
Port int
Username string
Password string
DB int
}
func (c *Redis) Validate() error {
switch {
case c.Host == "":
return wrapValidationError("redis", errors.New("host cannot be empty"))
case c.Port == 0:
return wrapValidationError("redis", errors.New("port cannot be empty"))
default:
return nil
}
}
func (c *Redis) BuildRedisOptions() *redis.Options {
if c == nil {
return nil
}
return &redis.Options{
Addr: net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.Port)),
Username: c.Username,
Password: c.Password,
DB: c.DB,
}
}
func (c *Redis) loadConfig(v *viper.Viper) error {
v.SetEnvPrefix("REDIS")
c.Host = v.GetString("HOST")
c.Port = v.GetInt("PORT")
c.DB = v.GetInt("DB")
c.Password = v.GetString("PASSWORD")
c.Username = v.GetString("USERNAME")
return nil
}
func (c *Redis) copy() *Redis {
if c == nil {
return nil
}
return &Redis{
Host: c.Host,
Port: c.Port,
Username: c.Username,
Password: c.Password,
DB: c.DB,
}
}