vegvisir/pkg/cache/redis_datastore.go
Piotr Biernat b0e492c163
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing
Fixes after code linters suggestions
2021-08-03 00:13:14 +02:00

61 lines
1.4 KiB
Go

// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package cache
import (
"strconv"
"time"
"github.com/go-redis/redis"
)
// NewRedisDatastore function
func NewRedisDatastore(host string, port int) *RedisDatastore {
return &RedisDatastore{
client: redis.NewClient(&redis.Options{
Addr: host + ":" + strconv.Itoa(port),
Password: "", // FIXME: use env or param
DB: 0, // FIXME: use env or param
}),
}
}
// RedisDatastore class
type RedisDatastore struct {
client *redis.Client
}
// SetKey function
func (ds *RedisDatastore) SetKey(key string, data interface{}, ttl int) error {
err := ds.client.Set(key, data, time.Duration(ttl)*time.Second).Err()
if err != nil {
return err
}
return nil
}
// GetKey function
func (ds *RedisDatastore) GetKey(key string) (interface{}, error) {
data, err := ds.client.Get(key).Result()
if err != nil {
return nil, err
}
return data, nil
}
// IsConnected function
func (ds *RedisDatastore) IsConnected() bool {
_, err := ds.client.Ping().Result()
return err == nil
}