cache

package
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 6 Imported by: 0

README

Cache Middleware

What it does

Caches eligible responses using an in-memory or custom store. It can reduce handler work and improve latency for repeated safe requests.

How to implement

package main

import (
	"github.com/oarkflow/fh"
	"github.com/oarkflow/fh/mw/cache"
)

func main() {
	app := fh.New()
	app.Use(cache.New(cache.Config{}))

	app.Get("/", func(c fh.Ctx) error {
		return c.Status(fh.StatusOK).SendString("ok")
	})
}

Impact

Can significantly reduce CPU/database load. Memory usage depends on response size, TTL, and key cardinality.

Ordering guidance

Run after request normalization and authentication only when cache keys include identity/tenant. Run before expensive handlers.

Production considerations

Be careful with personalized responses. Include tenant/user/version/query in cache keys. Respect cache-control rules and avoid caching sensitive data.

Persistent storage

For a cache that survives process restarts, construct kv.NewFileStore(dir, kv.WithMaxEntrySize(maxEntryBytes), kv.WithFileGCInterval(gcInterval)) and pass it as cache.Config.Store. Store is a kv.Store; kv.NewMemoryStore remains the default when left nil.

Documentation

Overview

Package cache provides bounded in-memory HTTP response caching.

Index

Constants

This section is empty.

Variables

View Source
var DefaultConfig = Config{TTL: time.Minute, MaxBodySize: 1 << 20, MaxEntries: 1024, Methods: []string{"GET", "HEAD"}}

Functions

func Delete

func Delete(store kv.Store, key string)

func New

func New(config ...Config) fh.HandlerFunc

func Set

func Set(store kv.Store, key string, e Entry)

Types

type Config

type Config struct {
	TTL                 time.Duration
	MaxBodySize         int
	MaxEntries          int
	Methods             []string
	VaryHeaders         []string
	AllowRequestCookies bool
	Store               kv.Store
	KeyGenerator        func(fh.Ctx) string
	Next                func(fh.Ctx) bool
}

type Entry

type Entry struct {
	Status           int
	ContentType      string
	Body             []byte
	Created, Expires time.Time
}

func Get

func Get(store kv.Store, key string) (Entry, bool)

Jump to

Keyboard shortcuts

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