tiny-url-ex/storage/redis.go

77 lines
1.5 KiB
Go

package storage
import (
"fmt"
"time"
"github.com/go-redis/redis"
)
const nonce = "go-tiny-url"
const (
// DATA domain used to store actual data
DATA string = "data"
// TOKEN domain used to store tokens
TOKEN string = "token"
)
// Client is a wrapper around the redis client
type Client struct {
client *redis.Client
}
// New returns new client
func New() (*Client, error) {
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
})
if _, err := client.Ping().Result(); err != nil {
return nil, err
}
return &Client{
client: client,
}, nil
}
// Close closes the connection
func (c *Client) Close() error {
return c.client.Close()
}
// Get returns a value from key or NIL
func (c *Client) Get(dom, key string) []byte {
redisKey := fmt.Sprintf("%s:%s:%s", nonce, dom, key)
val, err := c.client.Get(redisKey).Result()
if err != nil {
return nil
}
return []byte(val)
}
// Set stores a value for a key (success state in return)
func (c *Client) Set(dom, key string, value string, exp ...time.Duration) bool {
redisKey := fmt.Sprintf("%s:%s:%s", nonce, dom, key)
var expiration time.Duration
if len(exp) > 0 {
expiration = exp[0]
}
return c.client.Set(redisKey, value, expiration).Err() == nil
}
// Del deletes the value for a key (success state in return)
func (c *Client) Del(dom, key string) bool {
redisKey := fmt.Sprintf("%s:%s:%s", nonce, dom, key)
return c.client.Del(redisKey).Err() == nil
}