cachita: github.com/gadelkareem/cachita Index | Examples | Files

package cachita

import "github.com/gadelkareem/cachita"

Index

Examples

Package Files

cache.go file.go memory.go

Constants

const FileIndex = "github.com/gadelkareem/cachita/file-index"

Variables

var (
    ErrNotFound = errors.New("cachita: cache not found")
    ErrExpired  = errors.New("cachita: cache expired")
)

func Id Uses

func Id(params ...string) string

func IsErrorOk Uses

func IsErrorOk(err error) bool

func TypeAssert Uses

func TypeAssert(source, target interface{}) (err error)

type Cache Uses

type Cache interface {
    Get(key string, i interface{}) error
    Put(key string, i interface{}, ttl time.Duration) error // ttl 0:default ttl, -1: keep forever
    Exists(key string) bool
    Invalidate(key string) error
}

Code:

cache := cachita.Memory()
err := cache.Put("cache_key", "some data", 1*time.Minute)
if err != nil {
    panic(err)
}

if cache.Exists("cache_key") {
    //do something
}

var holder string
err = cache.Get("cache_key", &holder)
if err != nil && err != cachita.ErrNotFound {
    panic(err)
}

fmt.Printf("%s", holder) //prints "some data"

err = cache.Invalidate("cache_key")
if err != nil {
    panic(err)
}

Output:

some data

func File Uses

func File() (Cache, error)

Code:

cache, err := cachita.File()
if err != nil {
    panic(err)
}

err = cache.Put("cache_key", "some data", 1*time.Minute)
if err != nil {
    panic(err)
}

var holder string
err = cache.Get("cache_key", &holder)
if err != nil && err != cachita.ErrNotFound {
    panic(err)
}

fmt.Printf("%s", holder) //prints "some data"

Output:

some data

func Memory Uses

func Memory() Cache

Code:

var u url.URL
cacheId := cachita.Id(u.Scheme, u.Host, u.RequestURI())
obj := make(map[string]interface{})
obj["test"] = "data"
err := cachita.Memory().Put(cacheId, obj, 0)
if err != nil {
    panic(err)
}

var cacheObj map[string]interface{}
err = cachita.Memory().Get(cacheId, &cacheObj)
if err != nil && err != cachita.ErrNotFound && err != cachita.ErrExpired {
    panic(err)
}
fmt.Printf("%+v", cacheObj)

Output:

map[test:data]

func NewFileCache Uses

func NewFileCache(dir string, ttl, tickerTtl time.Duration) (Cache, error)

func NewMemoryCache Uses

func NewMemoryCache(ttl, tickerTtl time.Duration) Cache

Code:

cache := cachita.NewMemoryCache(1*time.Millisecond, 1*time.Minute) //default ttl 1 millisecond

err := cache.Put("cache_key", "some data", 0) //ttl = 0 means use default
if err != nil {
    panic(err)
}

time.Sleep(2 * time.Millisecond)
fmt.Printf("%t", cache.Exists("cache_key"))

Output:

false

Package cachita imports 13 packages (graph). Updated 2018-04-23. Refresh now. Tools for package owners.