A web blog and personal homepage engine written in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

59 lines
1.3 KiB

// Package cache provides optional Redis cache support.
package cache
import (
"fmt"
"errors"
"context"
"time"
redis "github.com/go-redis/redis/v8"
"git.kirsle.net/apps/gophertype/pkg/settings"
)
// Global Redis configuration.
var (
RedisHost = "localhost"
RedisPort = 6379
RedisDB = 0
RedisClient *redis.Client
ready bool
)
// Error codes
var (
ErrNotReady = errors.New("RedisClient not ready")
)
// Connect to Redis after loading the details from the site's settings.json.
func Connect() error {
set := settings.Current
if set.RedisEnabled {
RedisClient = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", set.RedisHost, set.RedisPort),
DB: set.RedisDB,
})
return nil
}
return errors.New("Redis not enabled in .settings.json")
}
// SetEx sets a cache key with expiration.
func SetEx(key string, value string, exp int64) error {
if RedisClient == nil {
return ErrNotReady
}
err := RedisClient.Set(context.Background(), key, value, time.Duration(exp) * time.Second).Err()
return err
}
// Get a cache key.
func Get(key string) (string, error) {
if RedisClient == nil {
return "", ErrNotReady
}
val, err := RedisClient.Get(context.Background(), key).Result()
return val, err
}