cachestore

package module
v1.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 14 Imported by: 1

README

Cache Store Open in Gitpod

Tests Status Go Report Card PkgGoDev

Cache messages to a database table.

Installation

go get -u github.com/dracory/cachestore

Setup

cacheStore = cachestore.NewStore(NewStoreOptions{
	DB:                 db,
	CacheTableName:     "my_cache",
	AutomigrateEnabled: false,
	DebugEnabled: false,
})

go cacheStore.ExpireCacheGoroutine()

Usage

  • Set value to cache with expiration
isSaved, err := cacheStore.Set("token", "ABCDEFGHIJKLMNOPQRSTVUXYZ", 60*60) // 1 hour (= 60 min * 60 sec)
if isSaved == false {
	log.Println("Saving failed")
	return
}
  • Get value from cache with default if not found
token, err := cacheStore.Get("token", "") // "" - default value, if the key has expired, or missing
  • Set and retrieve complex value as JSON
isSaved, err := cacheStore.Set("token", map[string]string{"first_name": "Jo"}, 60*60) // 1 hour (= 60 min * 60 sec)
if isSaved == false {
	log.Println("Saving failed")
	return
}

value, err := store.GetJSON("hello", "")

if err != nil {
	log.Fatalf("Getting JSON failed:" + err.Error())
}

result := value.(map[string]interface{})

log.Println(result["first_name"])

Changelog

2022.12.17 - Changed setup for new store

2021.12.31 - Fixed GetJSON and added tests

2021.12.29 - Cache ID updated to nano precission

2021.12.27 - Cache key length increased

2021.12.12 - Added license

2021.12.12 - Added tests badge

2021.12.12 - Fixed bug where DB scanner was returning empty values

2021.12.09 - Added support for DB dialects

2021.09.11 - Removed GORM dependency and moved to the standard library

Documentation

Index

Constants

View Source
const (
	COLUMN_ID         = "id"
	COLUMN_KEY        = "cache_key"
	COLUMN_VALUE      = "cache_value"
	COLUMN_EXPIRES_AT = "expires_at"
	COLUMN_CREATED_AT = "created_at"
	COLUMN_UPDATED_AT = "updated_at"
	COLUMN_DELETED_AT = "soft_deleted_at"
)

Column names for the cache table

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {
	orm.ShortID
	soft_delete.SoftDeletesMaxDate

	KeyField       string     `db:"cache_key"`
	ValueField     string     `db:"cache_value"`
	ExpiresAtField *time.Time `db:"expires_at"`

	CreatedAtField time.Time `db:"created_at"`
	UpdatedAtField time.Time `db:"updated_at"`
}

Cache type

func (*Cache) CreatedAt

func (c *Cache) CreatedAt() time.Time

CreatedAt returns the creation timestamp

func (*Cache) DeletedAt

func (c *Cache) DeletedAt() *time.Time

DeletedAt returns the soft delete timestamp (nil if not deleted)

func (*Cache) ExpiresAt

func (c *Cache) ExpiresAt() *time.Time

ExpiresAt returns the expiration time

func (*Cache) Key

func (c *Cache) Key() string

Key returns the cache key

func (*Cache) SetExpiresAt added in v1.3.0

func (c *Cache) SetExpiresAt(t *time.Time)

SetExpiresAt sets the expiration time

func (*Cache) SetKey added in v1.3.0

func (c *Cache) SetKey(key string)

SetKey sets the cache key

func (*Cache) SetValue added in v1.3.0

func (c *Cache) SetValue(value string)

SetValue sets the cache value

func (*Cache) UpdatedAt

func (c *Cache) UpdatedAt() time.Time

UpdatedAt returns the last update timestamp

func (*Cache) Value

func (c *Cache) Value() string

Value returns the cache value

type NewStoreOptions

type NewStoreOptions struct {
	DB                 *sql.DB
	CacheTableName     string
	AutomigrateEnabled bool
	DebugEnabled       bool
}

NewStoreOptions define the options for creating a new cache store

type StoreInterface

type StoreInterface interface {
	// EnableDebug enables or disables debug mode
	EnableDebug(debugEnabled bool)

	// GetCacheTableName returns the cache table name
	GetCacheTableName() string

	// SetCacheTableName sets the cache table name
	SetCacheTableName(cacheTableName string)

	// MigrateDown drops the cache table
	MigrateDown(ctx context.Context, tx ...*sql.Tx) error

	// MigrateUp creates the cache table
	MigrateUp(ctx context.Context, tx ...*sql.Tx) error

	// ExpireCacheGoroutine runs the cache expiration goroutine
	ExpireCacheGoroutine(ctx context.Context) error

	// Set stores a value in the cache
	Set(key string, value string, seconds int64) error

	// Get retrieves a value from the cache
	Get(key string, valueDefault string) (string, error)

	// SetJSON stores a JSON value in the cache
	SetJSON(key string, value any, seconds int64) error

	// GetJSON retrieves a JSON value from the cache
	GetJSON(key string, valueDefault any) (any, error)

	// Remove removes a value from the cache
	Remove(key string) error

	// FindByKey finds a cache entry by key
	FindByKey(key string) (*Cache, error)
}

StoreInterface defines the interface for a cache store

func NewStore

func NewStore(opts NewStoreOptions) (StoreInterface, error)

NewStore creates a new cache store

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL