ddns/hosts/redis.go
Philipp Böhm 6af394aa2f refactor ddns into several packages and add tests for most important
components

WIP

restructure code into separate packages + add tests for request handling

more documentation for methods

remove useless comment
2017-07-02 20:46:28 +02:00

76 lines
1.4 KiB
Go

package hosts
import (
"../config"
"github.com/garyburd/redigo/redis"
"time"
)
type RedisBackend struct {
expirationSeconds int
pool *redis.Pool
}
func NewRedisBackend(config *config.Config) *RedisBackend {
return &RedisBackend{
expirationSeconds: config.HostExpirationDays * 24 * 60 * 60,
pool: &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", config.RedisHost)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
},
}
}
func (r *RedisBackend) Close() {
r.pool.Close()
}
func (r *RedisBackend) GetHost(name string) (*Host, error) {
conn := r.pool.Get()
defer conn.Close()
host := Host{Hostname: name}
var err error
var data []interface{}
if data, err = redis.Values(conn.Do("HGETALL", host.Hostname)); err != nil {
return nil, err
}
if err = redis.ScanStruct(data, &host); err != nil {
return nil, err
}
return &host, nil
}
func (r *RedisBackend) SetHost(host *Host) error {
conn := r.pool.Get()
defer conn.Close()
var err error
if _, err = conn.Do("HMSET", redis.Args{}.Add(host.Hostname).AddFlat(host)...); err != nil {
return err
}
if _, err = conn.Do("EXPIRE", host.Hostname, r.expirationSeconds); err != nil {
return err
}
return nil
}