cache

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2021 License: MIT Imports: 12 Imported by: 0

README

gin-cache gin's middleware

GoDoc 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)
	}
}
Donation

if package help you a lot,you can support us by:

Alipay

alipay

WeChat Pay

wxpay

Documentation

Index

Constants

This section is empty.

Variables

View Source
var PageCachePrefix = "gincache.page.cache:"

PageCachePrefix default page cache key prefix

Functions

func Cache

func Cache(store persist.Store, expire time.Duration, handle gin.HandlerFunc, opts ...Option) gin.HandlerFunc

Cache user must pass store and store expiration time to cache and with custom option. default caching response with uri, which use PageCachePrefix

func CacheWithRequestPath

func CacheWithRequestPath(store persist.Store, expire time.Duration, handle gin.HandlerFunc,
	opts ...Option) gin.HandlerFunc

CacheWithRequestPath a shortcut function for caching response with url path, which discard the query params

func CacheWithRequestURI

func CacheWithRequestURI(store persist.Store, expire time.Duration, handle gin.HandlerFunc,
	opts ...Option) gin.HandlerFunc

CacheWithRequestURI a shortcut function for caching response with uri

func GenerateKeyWithPrefix

func GenerateKeyWithPrefix(prefix, key string) string

GenerateKeyWithPrefix generate key with GenerateKeyWithPrefix and u, if key is larger than 200,it will use sha1.Sum key like: prefix+u or prefix+sha1(u)

func GenerateRequestPathKey

func GenerateRequestPathKey(c *gin.Context) (string, bool)

GenerateRequestPathKey generate key with PageCachePrefix and request Path

func GenerateRequestURIKey

func GenerateRequestURIKey(c *gin.Context) (string, bool)

GenerateRequestURIKey generate key with PageCachePrefix and request uri

Types

type BodyCache

type BodyCache struct {
	Status int
	Header http.Header
	Data   []byte
	// contains filtered or unexported fields
}

BodyCache body cache store

func (*BodyCache) MarshalBinary added in v0.0.5

func (b *BodyCache) MarshalBinary() ([]byte, error)

func (*BodyCache) UnmarshalBinary added in v0.0.5

func (b *BodyCache) UnmarshalBinary(data []byte) error

type BodyWriter

type BodyWriter struct {
	gin.ResponseWriter
	// contains filtered or unexported fields
}

BodyWriter dup response writer body

func (*BodyWriter) Write

func (w *BodyWriter) Write(b []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply.

func (*BodyWriter) WriteString

func (w *BodyWriter) WriteString(s string) (int, error)

WriteString the string into the response body.

type Config

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

Config config for cache

type Discard

type Discard struct{}

Discard is an logger on which all Write calls succeed without doing anything.

func NewDiscard

func NewDiscard() Discard

NewDiscard a discard logger on which always succeed without doing anything

func (Discard) DPanicf

func (sf Discard) DPanicf(string, ...interface{})

DPanicf implement Logger interface.

func (Discard) Debugf

func (sf Discard) Debugf(string, ...interface{})

Debugf implement Logger interface.

func (Discard) Errorf

func (sf Discard) Errorf(string, ...interface{})

Errorf implement Logger interface.

func (Discard) Fatalf

func (sf Discard) Fatalf(string, ...interface{})

Fatalf implement Logger interface.

func (Discard) Infof

func (sf Discard) Infof(string, ...interface{})

Infof implement Logger interface.

func (Discard) Warnf

func (sf Discard) Warnf(string, ...interface{})

Warnf implement Logger interface.

type Encoding added in v0.0.5

type Encoding interface {
	Marshal(v interface{}) ([]byte, error)
	Unmarshal(data []byte, v interface{}) error
}

Encoding interface

type JSONEncoding added in v0.0.5

type JSONEncoding struct{}

func (JSONEncoding) Marshal added in v0.0.5

func (JSONEncoding) Marshal(v interface{}) ([]byte, error)

func (JSONEncoding) Unmarshal added in v0.0.5

func (JSONEncoding) Unmarshal(data []byte, v interface{}) error

type JSONGzipEncoding added in v0.0.5

type JSONGzipEncoding struct{}

func (JSONGzipEncoding) Marshal added in v0.0.5

func (JSONGzipEncoding) Marshal(v interface{}) ([]byte, error)

func (JSONGzipEncoding) Unmarshal added in v0.0.5

func (JSONGzipEncoding) Unmarshal(data []byte, v interface{}) error

type Logger

type Logger interface {
	Errorf(format string, args ...interface{})
}

Logger logger interface

type Option

type Option func(c *Config)

Option custom option

func WithBodyCachePool

func WithBodyCachePool(p Pool) Option

WithBodyCachePool custom body cache pool, default is private cache pool.

func WithEncoding added in v0.0.5

func WithEncoding(encode Encoding) Option

WithEncoding custom Encoding, default is JSONEncoding.

func WithGenerateKey

func WithGenerateKey(f func(c *gin.Context) (string, bool)) Option

WithGenerateKey custom generate key ,default is GenerateRequestURIKey.

func WithLogger

func WithLogger(l Logger) Option

WithLogger custom logger, default is Discard.

func WithRandDuration

func WithRandDuration(rand func() time.Duration) Option

WithRandDuration custom rand duration for expire, default return zero expiration time always expire + rand()

func WithSingleflight

func WithSingleflight(group *singleflight.Group) Option

WithSingleflight custom single flight group, default is private single flight group.

type Pool

type Pool interface {
	Get() *BodyCache
	Put(*BodyCache)
}

Pool BodyCache pool

func NewPool

func NewPool() Pool

NewPool new pool for BodyCache

Directories

Path Synopsis
_example

Jump to

Keyboard shortcuts

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