gocache

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: May 30, 2022 License: MIT Imports: 9 Imported by: 0

README

Simple cache for Golang


Package gocache provides a simple cache for web services

  • It uses in-memory storage by default (in a map[string]*Item) & temporary disk storage for items larger than a certain treshold
  • It is concurrency-friendly (using sync.RWMutex)
  • Key-Value
  • It encodes data as JSON under the hood
  • It tries to be as developer-friendly as possible

Features
Storage
  • Set lifespan on data
  • In memory cache
  • Caching large data to temporary files
  • Something similar to SQL transactions (rollback / commit)
Web
  • Handle HTTP request/response caching (by using some of the request data to generate unique ID and storing prepared HTTP response)
Logging
  • Request log
  • Error log
Querying
  • Filters for read requests

Documentation

Overview

Package gocache provides a simple cache

Index

Constants

View Source
const (
	KeyWriteOne uint8 = iota
	KeyEraseOne uint8 = iota
	KeyReadOne  uint8 = iota
)

Keys to identify request types

Variables

View Source
var ErrEmptyItem = errors.New("item is empty, there's no data or file associated with it")

ErrEmptyItem occurs for attemps to decode items that don't have any data

View Source
var ErrMaxItemsReached = errors.New("the maximum number of items has been reached")

ErrMaxItemsReached occurs when the request fails because the maximum number of items in the map has been reached It is defined in the maxitems CacheConfig field

View Source
var ErrUnknownID = errors.New("ID was not found")

ErrUnknownID occurs when no resource was found for a given ID

Functions

func CacheHTTP

func CacheHTTP(in http.Handler, identifier RequestIdentifier, cacheConfig CacheConfig) (http.Handler, error)

CacheHTTP can be used to filter requests so that if they have a cached response already they are answered directly

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache provides in-memory data storage Use the NewCache func to create a new cache

func NewCache

func NewCache(config CacheConfig) (*Cache, error)

NewCache instantiates a cache it calls make(map[string]*item to avoid assigning to nil map for the cache.items field) it also creates a local directory to store temporary files

func (*Cache) EraseOne

func (c *Cache) EraseOne(eoreq EraseOneRequest) error

EraseOne deletes an item if the request is valid

func (*Cache) ReadOne

func (c *Cache) ReadOne(roreq ReadOneRequest) (*Item, error)

ReadOne reads an item if the request is valid

func (*Cache) Start

func (c *Cache) Start()

Start prepares the cache for being used it starts the cleanup loop that will take care of removing expired items

func (*Cache) Stop

func (c *Cache) Stop()

Stop gracefully stops the cache

func (*Cache) WriteOne

func (c *Cache) WriteOne(woreq WriteOneRequest) error

WriteOne creates or update an item if the request is valid when the item exceeds the size limit, it is stored to a temporary file

type CacheConfig

type CacheConfig struct {
	ID              string
	MaxItems        int
	SizeLimit       int
	CleanupInterval time.Duration
}

CacheConfig holds the cache configuration id sets the cache id (used for error tracing and local file paths related to the cache) (default: time.Now()) interval sets the cleanup interval for the cleanup routine (default: one second) maxitems sets the maximum number of items (default: one hundred thousand) sizelimit sets the number of bytes for an item to be considered too big for in-memory (default: 500 kilobyte) an item with a size that exceeds the sizelimit will be stored a to a file

type CachedResponse

type CachedResponse struct {
	StatusCode int
	Header     http.Header
	Cookies    []*http.Cookie
	Body       []byte
}

CachedResponse holds data necessary for responding to identified http requests

type DefaultRequestIdentifier

type DefaultRequestIdentifier struct {
	// contains filtered or unexported fields
}

DefaultRequestIdentifier implements the RequestIdentifier interface

func NewRequestIdentifier

func NewRequestIdentifier(itemTTL time.Duration, identifyFunc func(*http.Request) string) *DefaultRequestIdentifier

NewRequestIdentifier instanciates a new DefaultRequestIdentifier

func (*DefaultRequestIdentifier) Identify

func (dri *DefaultRequestIdentifier) Identify(r *http.Request) string

Identify returns an ID based on the identity func defined

func (*DefaultRequestIdentifier) ItemTTL

func (dri *DefaultRequestIdentifier) ItemTTL() time.Duration

ItemTTL defines for how long the response will be stored in the cache

type EraseOneRequest

type EraseOneRequest struct {
	ItemID string
	// contains filtered or unexported fields
}

EraseOneRequest represents a request from the client to delete an item in the cache

type Item

type Item struct {
	// contains filtered or unexported fields
}

Item represents a single entity in the list (for ex: a user in a list of users) make sure every item has a unique ID

func (*Item) DecodeInto

func (i *Item) DecodeInto(intoptr interface{}) error

DecodeInto decodes the item in the provided variable (must be a pointer)

type ReadOneRequest

type ReadOneRequest struct {
	ItemID string
	// contains filtered or unexported fields
}

ReadOneRequest represents a request from the client to read an item in the cache

type RequestIdentifier

type RequestIdentifier interface {
	Identify(r *http.Request) string
	ItemTTL() time.Duration
}

RequestIdentifier generates an ID from a http request and provides the item ttl in the cache

type WriteOneRequest

type WriteOneRequest struct {
	ItemID string
	Value  interface{}
	Expiry time.Time
	// contains filtered or unexported fields
}

WriteOneRequest represents a request from the client to add or update an item in the cache Write operations don't check if the item already exists: so if you want to make sure an item can't be overwritten, check if the item exists before

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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