nurse/protocols/redis/client.go

47 lines
1 KiB
Go
Raw Normal View History

2022-04-28 16:35:02 +00:00
package redis
import (
"strconv"
"github.com/mitchellh/mapstructure"
"github.com/redis/go-redis/v9"
2022-04-28 16:35:02 +00:00
2022-09-22 09:46:36 +00:00
"code.icb4dc0.de/prskr/nurse/config"
"code.icb4dc0.de/prskr/nurse/grammar"
2022-04-28 16:35:02 +00:00
)
func clientFromParam(p grammar.Param, srvLookup config.ServerLookup) (redis.UniversalClient, error) {
2022-04-28 16:35:02 +00:00
if srvName, err := p.AsString(); err != nil {
return nil, err
} else if srv, err := srvLookup.Lookup(srvName); err != nil {
2022-04-28 16:35:02 +00:00
return nil, err
} else if redisCli, err := ClientForServer(srv); err != nil {
return nil, err
} else {
return redisCli, nil
}
}
func ClientForServer(srv *config.Server) (redis.UniversalClient, error) {
opts := &redis.UniversalOptions{
Addrs: srv.Hosts,
}
if pathLen := len(srv.Path); pathLen > 0 {
if db, err := strconv.Atoi(srv.Path[0]); err == nil {
opts.DB = db
}
}
if err := mapstructure.Decode(srv.Args, opts); err != nil {
return nil, err
}
if srv.Credentials != nil {
opts.Username = srv.Credentials.Username
opts.Password = *srv.Credentials.Password
}
2022-04-28 16:35:02 +00:00
return redis.NewUniversalClient(opts), nil
}