package db import ( "fmt" "github.com/go-redis/redis" ) const NONCE = "go-tiny-url" var domain = "data" 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(key string) []byte { // 1. Try to get if val, err := (*redis.Client)(c).Get(fmt.Sprintf("%s:%s:%s", NONCE, domain, 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(key string, value string) bool { // 1. Try to set if (*redis.Client)(c).Set(fmt.Sprintf("%s:%s:%s", NONCE, domain, key), value, 0).Err() != nil { // 2. failure return false } // 3. success return true } // deletes the value for a key (success state in return) func (c *db) Del(key string) bool { // 1. Try to set if (*redis.Client)(c).Del(fmt.Sprintf("%s:%s:%s", NONCE, domain, key)).Err() != nil { // 2. failure return false } // 3. success return true } // Switch following operations to DATA dataset func (c *db) SwitchData() { domain = "data" } // Switch following operations to AUTH dataset func (c *db) SwitchAuth() { domain = "auth" }