82 lines
1.4 KiB
Go
82 lines
1.4 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/go-redis/redis"
|
|
"time"
|
|
)
|
|
|
|
const NONCE = "go-tiny-url"
|
|
|
|
type Domain string
|
|
|
|
const (
|
|
DATA Domain = "data"
|
|
TOKEN Domain = "token"
|
|
)
|
|
|
|
type db redis.Client
|
|
|
|
// Returns a connected client to dataset
|
|
func Connect() *db {
|
|
|
|
cli := redis.NewClient(&redis.Options{
|
|
Addr: "127.0.0.1:6379",
|
|
Password: "",
|
|
DB: 0,
|
|
})
|
|
|
|
if _, err := cli.Ping().Result(); err != nil {
|
|
return nil
|
|
}
|
|
|
|
return (*db)(cli)
|
|
}
|
|
|
|
// returns value from key (nil if nothing)
|
|
func (c *db) Get(dom Domain, key string) []byte {
|
|
|
|
// 1. Try to get
|
|
if val, err := (*redis.Client)(c).Get(fmt.Sprintf("%s:%s:%s", NONCE, dom, key)).Result(); err != nil {
|
|
// 2. nil if nothing found
|
|
return nil
|
|
} else {
|
|
// 3. return if found
|
|
return []byte(val)
|
|
}
|
|
|
|
}
|
|
|
|
// stores a value for a key (success state in return)
|
|
func (c *db) Set(dom Domain, key string, value string, exp ...time.Duration) bool {
|
|
|
|
var expiration time.Duration = 0
|
|
if len(exp) > 0 {
|
|
expiration = exp[0]
|
|
}
|
|
|
|
// 1. Try to set
|
|
if (*redis.Client)(c).Set(fmt.Sprintf("%s:%s:%s", NONCE, dom, key), value, expiration).Err() != nil {
|
|
// 2. failure
|
|
return false
|
|
}
|
|
|
|
// 3. success
|
|
return true
|
|
|
|
}
|
|
|
|
// deletes the value for a key (success state in return)
|
|
func (c *db) Del(dom Domain, key string) bool {
|
|
|
|
// 1. Try to set
|
|
if (*redis.Client)(c).Del(fmt.Sprintf("%s:%s:%s", NONCE, dom, key)).Err() != nil {
|
|
// 2. failure
|
|
return false
|
|
}
|
|
|
|
// 3. success
|
|
return true
|
|
|
|
}
|