cache

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2021 License: MIT Imports: 10 Imported by: 3

README

Cache

Cache manager with default file and redis driver. this package contains rate limiter and verification code driver.

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.

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, redis host, maxIdle, maxActive and db number to constructor function.

import "github.com/bopher/cache"
if rCache := cache.NewRedisCache("myApp", "localhost:6379", 50, 10000, 1); rCache != nil {
  // Cache driver created
} else {
  panic("failed to build cache driver")
}

Usage

Cache interface contains following methods:

Put

Put a new value to cache.

// Signature:
Put(key string, value interface{}, ttl time.Duration) bool

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

Put a new value to cache with infinite ttl.

// Signature:
PutForever(key string, value interface{}) bool

// Example:
ok := rCache.Put("total-users", 5000000)
Set

Change value of cache item

// Signature:
Set(key string, value interface{}) bool

// Example:
ok := rCache.Set("total-users", 5005)
Get

Get item from cache. Get function return cache item as interface{}. if you need get cache item with type use helper get functions described later.

// Signature:
Get(key string) interface{}

// Example:
v := rCache.Get("total-users")
Pull

Get item from cache and remove it

// Signature:
Pull(key string) interface{}

// Example:
v := rCache.Pull("total-users")
Exists

Check if item exists in cache

// Signature:
Exists(key string) bool

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

Delete item from cache.

// Signature:
Forget(key string) bool

// Example:
deleted := rCache.Forget("total-users")
TTL

Get cache item ttl.

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

// Example:
ttl := rCache.TTL("total-users")
Increment

Increment numeric item in cache.

// Signature:
Increment(key string) bool

// Example:
ok := rCache.Increment("total-users")
IncrementBy

Increment numeric item in cache by number.

// Signature:
IncrementBy(key string, value interface{}) bool

// Example:
ok := rCache.IncrementBy("total-users", 10)
Decrement

Decrement numeric item in cache.

// Signature:
Decrement(key string) bool

// Example:
ok := rCache.Decrement("total-users")
DecrementBy

Decrement numeric item in cache by number.

DecrementBy(key string, value interface{}) bool
Get By Type Methods

Helper get methods return fallback value if value not exists in cache.

// Bool parse dependency as boolean
Bool(key string, fallback bool) bool
// Int parse dependency as int
Int(key string, fallback int) int
// Int8 parse dependency as int8
Int8(key string, fallback int8) int8
// Int16 parse dependency as int16
Int16(key string, fallback int16) int16
// Int32 parse dependency as int32
Int32(key string, fallback int32) int32
// Int64 parse dependency as int64
Int64(key string, fallback int64) int64
// UInt parse dependency as uint
UInt(key string, fallback uint) uint
// UInt8 parse dependency as uint8
UInt8(key string, fallback uint8) uint8
// UInt16 parse dependency as uint16
UInt16(key string, fallback uint16) uint16
// UInt32 parse dependency as uint32
UInt32(key string, fallback uint32) uint32
// UInt64 parse dependency as uint64
UInt64(key string, fallback uint64) uint64
// Float32 parse dependency as float64
Float32(key string, fallback float32) float32
// Float64 parse dependency as float64
Float64(key string, fallback float64) float64
// String parse dependency as string
String(key string, fallback string) string
// Bytes parse dependency as bytes array
Bytes(key string, fallback []byte) []byte

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)

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

Usage

Rate limiter interface contains following methods:

Hit

Decrease the allowed times.

// Signature:
Hit()

// Example:
limiter.Hit()
Lock

Lock rate limiter.

// Signature:
Lock()

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

Reset rate limiter.

// Signature:
Reset()

// Example:
limiter.Reset()
MustLock

Check if rate limiter must lock access.

// Signature:
MustLock() bool

// Example:
if limiter.MustLock() {
  // Block access
}
TotalAttempts

Get user attempts count.

// Signature:
TotalAttempts() uint32

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

Get user retries left.

// Signature:
RetriesLeft() uint32

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

Get time until unlock.

// Signature:
AvailableIn() time.Duration

// Example:
availableIn := 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)

// Example:
import "github.com/bopher/cache"
vCode := 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)

// Example:
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()

// Example:
vCode.Clear()
Get

Get code.

// Signature:
Get() string

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

Exists check if code exists in cache and not empty.

// Signature:
Exists() bool

// Example:
exists := vCode.Exists()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// Put a new value to cache
	Put(key string, value interface{}, ttl time.Duration) bool
	// PutForever put value with infinite ttl
	PutForever(key string, value interface{}) bool
	// Set Change value of cache item
	Set(key string, value interface{}) bool
	// Get item from cache
	Get(key string) interface{}
	// Pull item from cache and remove it
	Pull(key string) interface{}
	// Check if item exists in cache
	Exists(key string) bool
	// Forget item from cache (delete item)
	Forget(key string) bool
	// TTL get cache item ttl
	TTL(key string) time.Duration
	// Bool parse dependency as boolean
	Bool(key string, fallback bool) bool
	// Int parse dependency as int
	Int(key string, fallback int) int
	// Int8 parse dependency as int8
	Int8(key string, fallback int8) int8
	// Int16 parse dependency as int16
	Int16(key string, fallback int16) int16
	// Int32 parse dependency as int32
	Int32(key string, fallback int32) int32
	// Int64 parse dependency as int64
	Int64(key string, fallback int64) int64
	// UInt parse dependency as uint
	UInt(key string, fallback uint) uint
	// UInt8 parse dependency as uint8
	UInt8(key string, fallback uint8) uint8
	// UInt16 parse dependency as uint16
	UInt16(key string, fallback uint16) uint16
	// UInt32 parse dependency as uint32
	UInt32(key string, fallback uint32) uint32
	// UInt64 parse dependency as uint64
	UInt64(key string, fallback uint64) uint64
	// Float32 parse dependency as float64
	Float32(key string, fallback float32) float32
	// Float64 parse dependency as float64
	Float64(key string, fallback float64) float64
	// String parse dependency as string
	String(key string, fallback string) string
	// Bytes parse dependency as bytes array
	Bytes(key string, fallback []byte) []byte
	// Increment numeric item in cache
	Increment(key string) bool
	// IncrementBy numeric item in cache by number
	IncrementBy(key string, value interface{}) bool
	// Decrement numeric item in cache
	Decrement(key string) bool
	// DecrementBy numeric item in cache by number
	DecrementBy(key string, value interface{}) bool
}

Cache interface for cache drivers.

func NewFileCache

func NewFileCache(prefix string, dir string) Cache

NewFileCache create a new file cache manager instance

func NewRedisCache

func NewRedisCache(prefix string, host string, maxIdle int, maxActive int, db uint8) Cache

NewRedisCache create a new redis cache manager instance

type RateLimiter

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

RateLimiter interface for rate limiter

func NewRateLimiter

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

NewRateLimiter create a new rate limiter

type VerificationCode

type VerificationCode interface {
	// Set set code
	Set(value string)
	// 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()
	// Get get code
	Get() string
	// Exists check if code exists
	Exists() bool
}

VerificationCode interface for verification code

func NewVerificationCode

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

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