gache

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2022 License: MIT Imports: 6 Imported by: 8

README

Gache

Gache is a dead simple file-based (or in-memory) cache library for Go with zero dependencies.

There are great caching libraries out there, but none of them fit my needs or not as simple as I'd like to. So I decided to write my own and share it with the world. 🐳

Work in progress, I wouldn't reccommend using it now

Installation

go get github.com/metafates/gache

Usage Example

package main

import (
	"encoding/json"
	"fmt"
	"github.com/metafates/gache"
	"net/http"
	"time"
)

type Pokemon struct {
	Height int
}

// Create new cache instance
var cache = gache.New[map[string]*Pokemon](&gache.Options{
	// Path to cache file
	// If not set, cache will be in-memory
	Path: ".cache/pokemons.json",

	// Lifetime of cache.
	// If not set, cache will never expire
	Lifetime: time.Hour,
})

// getPokemon will get a pokemon by name from API
// Gonna Cache Em' All!
func getPokemon(name string) (*Pokemon, error) {
	// check if Pokémon is in cache
	pokemons, expired, err := cache.Get()
	if err != nil {
		return nil, err
	}

	// if cache is expired, or Pokémon wasn't cached
	// Fetch it from API
	if pokemon, ok := pokemons[name]; !expired && ok {
		return pokemon, nil
	}

	// bla-bla-bla, boring stuff, etc...
	resp, err := http.Get("https://pokeapi.co/api/v2/pokemon/" + name)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	var pokemon Pokemon
	if err := json.NewDecoder(resp.Body).Decode(&pokemon); err != nil {
		return nil, err
	}

	// okay, we got our Pokémon, let's cache it
	pokemons[name] = &pokemon
	_ = cache.Set(pokemons)

	return &pokemon, nil
}

func main() {
	start := time.Now()
	for i := 0; i < 3; i++ {
		_, _ = getPokemon("pikachu")
	}
	fmt.Println(time.Since(start))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}

Cache is a generic thread-safe cache that can be used to cache any type of data. It is used to cache data that is expensive to fetch, such as API responses. Cached data is stored in a JSON file, and is automatically expired after a certain amount of time (if lifetime is specified)

func New

func New[T any](options *Options) *Cache[T]

New returns a new Cache[T] instance.

func (*Cache[T]) Get

func (g *Cache[T]) Get() (cached T, expired bool, err error)

Get returns the value of the cache. If initialization fails, it will return an error. In memory-only mode it will never fail.

func (*Cache[T]) Set

func (g *Cache[T]) Set(value T) error

Set sets the value of the cache. If initialization or marshalling fails, it will return an error. In memory-only mode it will never fail. It will restart the cache's lifetime.

type Decoder

type Decoder interface {
	// Decode decodes the given data and writes it to the given writer.
	Decode(r io.Reader, data any) error
}

Decoder is an interface that wraps Decode method.

type Encoder

type Encoder interface {
	// Encode encodes the given data and writes it to the given writer.
	Encode(w io.Writer, data any) error
}

Encoder is an interface that wraps Encode method.

type FileSystem

type FileSystem interface {
	OpenFile(name string, flag int, perm os.FileMode) (io.ReadWriteCloser, error)
	MkdirAll(path string, perm os.FileMode) error
}

type Options

type Options struct {
	// Path to the file to store the cache.
	// If not specified (empty string), the cache will be stored in memory.
	Path string

	// Lifetime is the time duration after which the cache expires.
	// Values below zero are treated as never expiring.
	// Defaults to -1.
	Lifetime time.Duration

	// FileSystem is a filesystem that is used to store the cache file.
	FileSystem FileSystem

	// Encoder is the encoder to use for the cache.
	Encoder Encoder

	// Decoder is the decoder to use for the cache.
	Decoder Decoder

	// ExpirationHook is a function that is called when the cache expires.
	ExpirationHook func()
}

Options is a struct that contains options for the cache.

Jump to

Keyboard shortcuts

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