cache

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2025 License: MIT Imports: 11 Imported by: 127

README

Cache middleware

Build Status codecov Go Report Card GoDoc

Gin middleware/handler to enable Cache.

Usage

Start using it

Download and install it:

go get github.com/gin-contrib/cache

Import it in your code:

import "github.com/gin-contrib/cache"
InMemory Example

See the example

package main

import (
  "fmt"
  "time"

  "github.com/gin-contrib/cache"
  "github.com/gin-contrib/cache/persistence"
  "github.com/gin-gonic/gin"
)

func main() {
  r := gin.Default()

  store := persistence.NewInMemoryStore(time.Second)

  r.GET("/ping", func(c *gin.Context) {
    c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
  })
  // Cached Page
  r.GET("/cache_ping", cache.CachePage(store, time.Minute, func(c *gin.Context) {
    c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
  }))

  // Listen and Server in 0.0.0.0:8080
  r.Run(":8080")
}

You can also use the Delete and Flush methods with the InMemory store:

// Delete a specific cache entry by key
err := store.Delete("your-cache-key")
if err != nil {
  // handle error
}

// Flush all cache entries
err = store.Flush()
if err != nil {
  // handle error
}
Redis Example

Here is a complete example using Redis as the cache backend with NewRedisCacheWithURL:

package main

import (
  "fmt"
  "time"

  "github.com/gin-contrib/cache"
  "github.com/gin-contrib/cache/persistence"
  "github.com/gin-gonic/gin"
)

func main() {
  r := gin.Default()

  // Basic usage:
  store := persistence.NewRedisCacheWithURL("redis://localhost:6379", time.Minute)

  // Advanced configuration with password and DB number:
  // store := persistence.NewRedisCacheWithURL("redis://:password@localhost:6379/0", time.Minute)

  r.GET("/ping", func(c *gin.Context) {
    c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
  })
  // Cached Page
  r.GET("/cache_ping", cache.CachePage(store, time.Minute, func(c *gin.Context) {
    c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
  }))

  // Listen and serve on 0.0.0.0:8080
  r.Run(":8080")
}

Documentation

Overview

Package cache provides middleware and utilities for HTTP response caching in Gin web applications. It supports pluggable cache stores, cache key generation, and decorators for page and site-level caching.

Index

Constants

View Source
const (
	CACHE_MIDDLEWARE_KEY = "gincontrib.cache"
)

Variables

View Source
var PageCachePrefix = "gincontrib.page.cache"

Functions

func Cache

func Cache(store *persistence.CacheStore) gin.HandlerFunc

Cache is a Gin middleware that injects the cache store into the request context.

func CachePage

func CachePage(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc

CachePage is a decorator that caches the response of the given handler based on the request URI. If a cached response exists, it is served directly. Otherwise, the handler is executed and its response is cached. If the context is aborted, the cache entry is deleted.

func CachePageAtomic

func CachePageAtomic(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc

CachePageAtomic is a decorator that wraps CachePage with a mutex to ensure atomic access. This prevents concurrent requests from generating duplicate cache entries for the same resource.

func CachePageWithoutHeader

func CachePageWithoutHeader(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc

CachePageWithoutHeader is a decorator that caches responses without restoring headers from the cache. Only the status and body are restored from the cache.

func CachePageWithoutQuery

func CachePageWithoutQuery(store persistence.CacheStore, expire time.Duration, handle gin.HandlerFunc) gin.HandlerFunc

CachePageWithoutQuery is a decorator that caches responses ignoring GET query parameters. The cache key is based only on the request path, so all queries to the same path share the cache.

func CreateKey

func CreateKey(u string) string

CreateKey generates a cache key for the given string using the package-specific prefix.

func RegisterResponseCacheGob

func RegisterResponseCacheGob()

RegisterResponseCacheGob registers the responseCache type with the encoding/gob package. This is required for gob-based cache stores to serialize/deserialize cached responses.

func SiteCache

func SiteCache(store persistence.CacheStore, expire time.Duration) gin.HandlerFunc

SiteCache is a Gin middleware that caches entire site responses based on the request URI. If a cached response exists, it is written directly; otherwise, the request proceeds as normal.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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