rc

package module
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2024 License: MIT Imports: 8 Imported by: 1

README

rc Go Reference build Coverage Code to Test Ratio Test Execution Time

rc is a response cache middleware for cache.

Usage

Prepare an instance that implements rc.Casher interface.

Then, generate the middleware ( func(next http.Handler) http.Handler ) with rc.New

package main

import (
    "log"
    "net/http"

    "github.com/2manymws/rc"
)

func main() {
    r := http.NewServeMux()
    r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello World"))
    })

    var c rc.Cacher = newMyCacher()
    m := rc.New(c)

    log.Fatal(http.ListenAndServe(":8080", m(r)))
}

Utility functions

See https://github.com/2manymws/rcutil

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrCacheExpired error = errors.New("cache expired")

ErrCacheExpired is returned if the cache is expired

View Source
var ErrCacheNotFound error = errors.New("cache not found")

ErrCacheNotFound is returned when the cache is not found

View Source
var ErrShouldNotUseCache error = errors.New("should not use cache")

ErrShouldNotUseCache is returned if should not use cache

Functions

func HandlerToRequester

func HandlerToRequester(h http.Handler) func(*http.Request) (*http.Response, error)

HandlerToRequester converts http.Handler to func(*http.Request) (*http.Response, error).

func New

func New(cacher Cacher, opts ...Option) func(next http.Handler) http.Handler

New returns a new response cache middleware.

Types

type Cacher

type Cacher interface {
	// Load loads the request/response cache.
	// If the cache is not found, it returns ErrCacheNotFound.
	// If not caching, it returns ErrNoCache.
	// If the cache is expired, it returns ErrCacheExpired.
	Load(req *http.Request) (cachedReq *http.Request, cachedRes *http.Response, err error)
	// Store stores the response cache.
	Store(req *http.Request, res *http.Response, expires time.Time) error
}

type Handler

type Handler interface {
	// Handle handles the request/response cache.
	Handle(req *http.Request, cachedReq *http.Request, cachedRes *http.Response, originRequester func(*http.Request) (*http.Response, error), now time.Time) (cacheUsed bool, res *http.Response, err error)
	// Storable returns whether the response is storable and the expiration time.
	Storable(req *http.Request, res *http.Response, now time.Time) (ok bool, expires time.Time)
}

type Option added in v0.6.0

type Option func(*cacheMw)

func UseRequestBody added in v0.9.1

func UseRequestBody() Option

UseRequestBody enables to use request body as cache key.

func WithLogger added in v0.6.0

func WithLogger(l *slog.Logger) Option

WithLogger sets logger (slog.Logger).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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