GithubHelp home page GithubHelp logo

go-cache's Introduction

Go Cache

MIT License Go Report Card Go Doc

Overview

Go Cache is a simple package to provide thread-safe in-memory caching in Go. It's my attempt to practice some of the patterns/philosophies found in these articles:

The code is tested, although standard caveats of using interface{} apply.
Personally, I'd recommend copying this package and replacing var T interface{} with whatever type you need to cache. I may add code generation in the future to make that process easier.

Example

package main

import (
        "fmt"
	"time"
        "github.com/ridgelines/go-cache"
)

func main() {
	c := cache.New()
	
	// empty the cache every hour
	c.ClearEvery(time.Hour)
	
	// add some items
	c.Set("key1", 1)
	c.Set("key2", 2)
	
	// add some items that will expire after 5 minutes
	c.Set("key3", 3, cache.Expire(time.Minute*5))
	c.Set("key4", 4,  cache.Expire(time.Minute*5))

	fmt.Println(c.Get("key1"))
	fmt.Println(c.Get("key2"))
	
	for _, key := range c.Keys() {
		fmt.Println(key)
	}
	
	for key, val := range c.Items() {
		fmt.Printf("%s: %v", key, val)
	}
	
	c.Delete("key1")
	
	if val, ok := c.GetOK("key2"); ok {
		fmt.Println(val)
	}
	
	c.Clear()
}

License

This work is published under the MIT license. Please see the LICENSE file for details.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.