Skip to content
This repository has been archived by the owner on Jun 11, 2024. It is now read-only.

things-go/gin-cache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

gin-cache gin's middleware

Go.Dev reference codecov Go Report Card Licence Tag Sourcegraph

Gin middleware/handler to enable Cache.

Usage

Start using it

Download and install it:

go get github.com/things-go/gin-cache

Import it in your code:

import cache "github.com/things-go/gin-cache"

Example

1. memory store

See the memory store

package main

import (
	"time"

	"github.com/gin-gonic/gin"
	inmemory "github.com/patrickmn/go-cache"

	cache "github.com/things-go/gin-cache"
	"github.com/things-go/gin-cache/persist/memory"
)

func main() {
	app := gin.New()

	app.GET("/hello",
		cache.CacheWithRequestURI(
			memory.NewStore(inmemory.New(time.Minute, time.Minute*10)),
			5*time.Second,
			func(c *gin.Context) {
				c.String(200, "hello world")
			},
		),
	)
	if err := app.Run(":8080"); err != nil {
		panic(err)
	}
}

2. redis store

See the redis store

package main

import (
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"

	cache "github.com/things-go/gin-cache"
	redisStore "github.com/things-go/gin-cache/persist/redis"
)

func main() {
	app := gin.New()

	store := redisStore.NewStore(redis.NewClient(&redis.Options{
		Network: "tcp",
		Addr:    "localhost:6379",
	}))

	app.GET("/hello",
		cache.CacheWithRequestPath(
			store,
			5*time.Second,
			func(c *gin.Context) {
				c.String(200, "hello world")
			},
		),
	)
	if err := app.Run(":8080"); err != nil {
		panic(err)
	}
}

3. custom key

See the custom key

package main

import (
	"time"

	"github.com/gin-gonic/gin"
	inmemory "github.com/patrickmn/go-cache"

	cache "github.com/things-go/gin-cache"
	"github.com/things-go/gin-cache/persist/memory"
)

func main() {
	app := gin.New()

	app.GET("/hello/:a/:b", custom())
	if err := app.Run(":8080"); err != nil {
		panic(err)
	}
}

func custom() gin.HandlerFunc {
	f := cache.CacheWithRequestURI(
		memory.NewStore(inmemory.New(time.Minute, time.Minute*10)),
		5*time.Second,
		func(c *gin.Context) {
			c.String(200, "hello world")
		},
		cache.WithGenerateKey(func(c *gin.Context) (string, bool) {
			return c.GetString("custom_key"), true
		}),
	)
	return func(c *gin.Context) {
		a := c.Param("a")
		b := c.Param("b")
		c.Set("custom_key", cache.GenerateKeyWithPrefix(cache.PageCachePrefix, a+":"+b))
		f(c)
	}
}

About

Gin middleware/handler to enable Cache

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages