cache

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2022 License: MIT Imports: 14 Imported by: 3

README

Cache

Cache manager with default file and redis driver (rate limiter and verification code manager included).

Create New Cache Driver

Cache library contains two different driver by default.

NOTE: You can extend your driver by implementing Cache interface.

Create File Based Driver

for creating file based driver you must pass file name prefix and cache directory to constructor function.

Note: You must call CleanFileExpiration function manually to clear expired records!

import "github.com/bopher/cache"
if fCache := cache.NewFileCache("myApp", "./caches"); fCache != nil {
  // Cache driver created
} else {
  panic("failed to build cache driver")
}
Create Redis Based Driver

for creating redis based driver you must pass prefix, and redis options to constructor function.

import "github.com/bopher/cache"
if rCache := cache.NewRedisCache("myApp", redis.Options{
  Addr: "localhost:6379",
}); rCache != nil {
  // Cache driver created
} else {
  panic("failed to build cache driver")
}
Create Colver DB Based Driver

for creating clover db based driver you must pass db and collection function.

Note: You must call CleanCloverExpiration function manually to clear expired records!

import "github.com/bopher/cache"
if clCache := cache.NewCloverCache(db, "_cache"); clCache != nil {
  // Cache driver created
} else {
  panic("failed to build cache driver")
}

Usage

Cache interface contains following methods:

Put

A new value to cache.

// Signature:
Put(key string, value any, ttl time.Duration) error

// Example:
err := rCache.Put("total-debt", 410203, 100 * time.Hour)
PutForever

Put value with infinite ttl.

// Signature:
PutForever(key string, value any) error

// Example:
err := rCache.PutForever("base-discount", 10)
Set

Change value of cache item and return false if item not exists (this. methods keep cache ttl).

Cation: set value on non exists item will generate error. please check if item exists before set or use put method instead!

// Signature:
Set(key string, value any) (bool, error)

// Example:
ok, err := rCache.Set("base-discount", 15)
Get

Get item from cache.

// Signature:
Get(key string) (any, error)

// Example:
v, err := rCache.Get("total-users")
Exists

Check if item exists in cache.

// Signature:
Exists(key string) (bool, error)

// Example:
exists, err := rCache.Exists("total-users");
Forget

Delete Item from cache.

// Signature:
Forget(key string) error

// Example:
err := rCache.Forget("total-users")
Pull

Item from cache and then remove it.

// Signature:
Pull(key string) (any, error)

// Example:
v, err := rCache.Pull("total-users")
TTL

Get cache item ttl. This method returns -1 if item not exists.

// Signature:
TTL(key string) (time.Duration, error)

// Example:
ttl, err := rCache.TTL("total-users")
Cast

Parse cache item as caster.

// Signature:
Cast(key string) (caster.Caster, error)

// Example:
c, err := rCache.Cast("total-users")
v, err := c.Int32()
IncrementFloat

Increment numeric item by float, return false if item not exists

// Signature:
IncrementFloat(key string, value float64) (bool, error)

// Example:
err := rCache.IncrementFloat("some-float", 0.01)
Increment

Increment numeric item by int, return false if item not exists

// Signature:
Increment(key string, value int64) (bool, error)

// Example:
err := rCache.Increment("some-number", 10)
DecrementFloat

Decrement numeric item by float, return false if item not exists

// Signature:
DecrementFloat(key string, value float64) (bool, error)

// Example:
err := rCache.DecrementFloat("some-float", 0.29)
Decrement

Decrement numeric item by int, return false if item not exists

// Signature:
Decrement(key string, value int64) (bool, error)

// Example:
err := rCache.Decrement("total-try", 1)

Create New Rate Limiter Driver

Note: Rate limiter based on cache, For creating rate limiter driver you must pass a cache driver instance to constructor function.

// Signature:
NewRateLimiter(key string, maxAttempts uint32, ttl time.Duration, cache Cache) (RateLimiter, error)

// Example: allow 3 attempts every 60 seconds
import "github.com/bopher/cache"
limiter, err := cache.NewRateLimiter("login-attempts", 3, 60 * time.Second, rCache)
Usage

Rate limiter interface contains following methods:

Hit

Decrease the allowed times.

// Signature:
Hit() error

// Example:
err := limiter.Hit()
Lock

Lock rate limiter.

// Signature:
Lock() error

// Example:
err := limiter.Lock() // no more attempts left
Reset

Reset rate limiter (clear total attempts).

// Signature:
Reset() error

// Example:
err := limiter.Reset()
Clear

Remove rate limiter record. call any method after clear with generate "NotExists" error!

// Signature:
Clear() error

// Example:
err := limiter.Clear()
MustLock

Check if rate limiter must lock access.

// Signature:
MustLock() (bool, error)

// Example:
if locked, _:= limiter.MustLock(), locked {
  // Block access
}
TotalAttempts

Get user attempts count.

// Signature:
TotalAttempts() (uint32, error)

// Example:
totalAtt, err := limiter.TotalAttempts() // 3
RetriesLeft

Get user retries left.

// Signature:
RetriesLeft() (uint32, error)

// Example:
leftRet, err := limiter.RetriesLeft() // 2
AvailableIn

Get time until unlock.

// Signature:
AvailableIn() (time.Duration, error)

// Example:
availableIn, err := limiter.AvailableIn()

Create New Verification Code Driver

verification code used for managing verification code sent to user.

Note: Verification code based on cache, For creating verification code driver you must pass a cache driver instance to constructor function.

// Signature:
NewVerificationCode(key string, ttl time.Duration, cache Cache) (VerificationCode, error)

// Example:
import "github.com/bopher/cache"
vCode, err := cache.NewVerificationCode("phone-verification", 5 * time.Minute, rCache)
Usage

Verification code interface contains following methods:

Set

Set code. You can set code directly or use generator methods.

// Signature:
Set(value string) error

// Example:
err := vCode.Set("ABD531")
Generate

Generate a random numeric code with 5 character length and set as code.

// Signature:
Generate() (string, error)

// Example:
code, err := vCode.Generate()
GenerateN

Generate a random numeric code with special character length and set as code.

// Signature:
GenerateN(count uint) (string, error)

// Example:
code, err := vCode.GenerateN(6)
Clear

Clear code from cache.

// Signature:
Clear() error

// Example:
err := vCode.Clear()
Get

Get code.

// Signature:
Get() (string, error)

// Example:
code, err := vCode.Get()
Exists

Exists check if code exists in cache and not empty.

// Signature:
Exists() (bool, error)

// Example:
exists, err := vCode.Exists()
TTL

Get token ttl.

// Signature:
TTL() (time.Duration, error)

// Example:
ttl, err := vCode.TTl()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanCloverExpiration added in v1.3.0

func CleanCloverExpiration(db *clover.DB, collection string) error

CleanCloverExpiration clean clover cache expired records

func CleanFileExpiration added in v1.3.1

func CleanFileExpiration(dir string) error

CleanFileExpiration clean file cache expired records

Types

type Cache

type Cache interface {
	// Put a new value to cache
	Put(key string, value any, ttl time.Duration) error
	// PutForever put value with infinite ttl
	PutForever(key string, value any) error
	// Set Change value of cache item, return false if item not exists
	Set(key string, value any) (bool, error)
	// Get item from cache
	Get(key string) (any, error)
	// Exists check if item exists in cache
	Exists(key string) (bool, error)
	// Forget delete Item from cache
	Forget(key string) error
	// Pull item from cache and remove it
	Pull(key string) (any, error)
	// TTL get cache item ttl. this method returns -1 if item not exists
	TTL(key string) (time.Duration, error)
	// Cast parse cache item as caster
	Cast(key string) (caster.Caster, error)
	// IncrementFloat increment numeric item by float, return false if item not exists
	IncrementFloat(key string, value float64) (bool, error)
	// Increment increment numeric item by int, return false if item not exists
	Increment(key string, value int64) (bool, error)
	// DecrementFloat decrement numeric item by float, return false if item not exists
	DecrementFloat(key string, value float64) (bool, error)
	// Decrement decrement numeric item by int, return false if item not exists
	Decrement(key string, value int64) (bool, error)
}

Cache interface for cache drivers.

func NewCloverCache added in v1.3.0

func NewCloverCache(db *clover.DB, collection string) Cache

NewCloverCache create a new clover db cache manager instance

func NewFileCache

func NewFileCache(prefix string, dir string) Cache

NewFileCache create a new file cache manager instance

func NewRedisCache

func NewRedisCache(prefix string, opt redis.Options) Cache

NewRedisCache create a new redis cache manager instance

type RateLimiter

type RateLimiter interface {
	// Hit decrease the allowed times
	Hit() error
	// Lock lock rate limiter
	Lock() error
	// Reset reset rate limiter
	Reset() error
	// Clear remove rate limiter record
	Clear() error
	// MustLock check if rate limiter must lock access
	MustLock() (bool, error)
	// TotalAttempts get user attempts count
	TotalAttempts() (uint32, error)
	// RetriesLeft get user retries left
	RetriesLeft() (uint32, error)
	// AvailableIn get time until unlock
	AvailableIn() (time.Duration, error)
}

RateLimiter interface for rate limiter

func NewRateLimiter

func NewRateLimiter(key string, maxAttempts uint32, ttl time.Duration, cache Cache) (RateLimiter, error)

NewRateLimiter create a new rate limiter

type VerificationCode

type VerificationCode interface {
	// Set set code
	Set(value string) error
	// Generate generate a random numeric code with 5 character length
	Generate() (string, error)
	// GenerateN generate a random numeric code with special character length
	GenerateN(count uint) (string, error)
	// Clear clear code
	Clear() error
	// Get get code
	Get() (string, error)
	// Exists check if code exists
	Exists() (bool, error)
	// TTL get ttl
	TTL() (time.Duration, error)
}

VerificationCode interface for verification code

func NewVerificationCode

func NewVerificationCode(key string, ttl time.Duration, cache Cache) (VerificationCode, error)

NewVerificationCode create a new verification code manager instance

Jump to

Keyboard shortcuts

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