forked from mtusi2026/mtusi2026lab7
91 lines
1.9 KiB
Go
91 lines
1.9 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/transportsecurity"
|
|
"net"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"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
|
|
}
|
|
opts := &redis.Options{
|
|
Addr: net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.Port)),
|
|
Username: c.Username,
|
|
Password: c.Password,
|
|
DB: c.DB,
|
|
DialTimeout: 200 * time.Millisecond,
|
|
ReadTimeout: 200 * time.Millisecond,
|
|
WriteTimeout: 200 * time.Millisecond,
|
|
PoolTimeout: 200 * time.Millisecond,
|
|
MaxRetries: -1,
|
|
DialerRetries: 1,
|
|
ContextTimeoutEnabled: true,
|
|
}
|
|
if transportsecurity.Enabled() {
|
|
tlsConfig, err := transportsecurity.Client()
|
|
if err != nil {
|
|
panic("invalid Redis TLS configuration")
|
|
}
|
|
opts.TLSConfig = tlsConfig
|
|
}
|
|
return opts
|
|
}
|
|
|
|
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")
|
|
if path := v.GetString("PASSWORD_FILE"); path != "" {
|
|
b, e := os.ReadFile(path)
|
|
if e != nil {
|
|
return fmt.Errorf("read cache credential: %w", e)
|
|
}
|
|
c.Password = strings.TrimSpace(string(b))
|
|
}
|
|
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,
|
|
}
|
|
}
|