Cache


Fiber용 Cache 미들웨어는 응답을 가로채서 캐시하도록 설계되었습니다. 이 미들웨어는 c.Path()를 고유 식별자로 사용하여 Body, Content-TypeStatusCode를 캐시합니다. Fiber 코어용 미들웨어를 만들어 주신 @codemicro에게 특별한 감사를 드립니다!

요청 지시문 Cache-Control: no-cache는 최신 응답을 반환하지만 여전히 캐시합니다. 항상 miss 캐시 상태를 얻게 됩니다. Cache-Control: no-store는 캐싱을 자제합니다. 항상 최신 응답을 얻게 됩니다.

Signatures

func New(config ...Config) fiber.Handler

Examples

Fiber 웹 프레임워크의 일부인 미들웨어 패키지를 가져옵니다.

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/cache"
)

Fiber 앱을 초기화한 후 다음과 같은 가능성을 사용할 수 있습니다:

// 기본 구성 초기화
app.Use(cache.New())

// 또는 사용자 지정을 위해 구성 확장
app.Use(cache.New(cache.Config{
    Next: func(c *fiber.Ctx) bool {
        return c.Query("noCache") == "true"
    },
    Expiration: 30 * time.Minute,
    CacheControl: true,
}))

또는 다음과 같이 사용자 지정 키와 만료 시간을 설정할 수 있습니다:

app.Use(cache.New(cache.Config{
    ExpirationGenerator: func(c *fiber.Ctx, cfg *cache.Config) time.Duration {
        newCacheTime, _ := strconv.Atoi(c.GetRespHeader("Cache-Time", "600"))
        return time.Second * time.Duration(newCacheTime)
    },
    KeyGenerator: func(c *fiber.Ctx) string {
		return utils.CopyString(c.Path())
    },
}))

app.Get("/", func(c *fiber.Ctx) error {
    c.Response().Header.Add("Cache-Time", "6000")
    return c.SendString("hi")
})

Config

Property
Type
Description
Default

Next

func(*fiber.Ctx) bool

Next는 캐시 항목을 생성하기 전에 실행되는 함수를 정의하며, 캐시 생성 없이 요청을 실행하는 데 사용할 수 있습니다. 항목이 이미 존재하는 경우 사용됩니다. 특정 경우에 캐시 기능을 완전히 우회하려면 skip 미들웨어를 사용해야 합니다.

nil

Expiration

time.Duration

Expiration은 캐시된 응답이 유지되는 시간입니다.

1 * time.Minute

CacheHeader

string

CacheHeader는 캐시 상태를 나타내는 응답 헤더의 헤더로, 가능한 반환 값은 "hit", "miss" 또는 "unreachable"입니다.

X-Cache

CacheControl

bool

CacheControl은 true로 설정된 경우 클라이언트 측 캐싱을 활성화합니다.

false

KeyGenerator

func(*fiber.Ctx) string

Key를 사용하면 사용자 지정 키를 생성할 수 있습니다.

func(c *fiber.Ctx) string { return utils.CopyString(c.Path()) }

ExpirationGenerator

func(*fiber.Ctx, *cache.Config) time.Duration

ExpirationGenerator를 사용하면 요청을 기반으로 사용자 지정 만료 키를 생성할 수 있습니다.

nil

Storage

fiber.Storage

Store는 미들웨어의 상태를 저장하는 데 사용됩니다.

In-memory store

Store (Deprecated)

fiber.Storage

Deprecated: 대신 Storage를 사용하세요.

In-memory store

Key (Deprecated)

func(*fiber.Ctx) string

Deprecated: 대신 KeyGenerator를 사용하세요.

nil

StoreResponseHeaders

bool

StoreResponseHeaders를 사용하면 다음 미들웨어 및 핸들러에서 생성한 추가 헤더를 저장할 수 있습니다.

false

MaxBytes

uint

MaxBytes는 캐시에 동시에 저장된 응답 본문의 최대 바이트 수입니다.

0 (제한 없음)

Methods

[]string

Methods는 캐시할 HTTP 메서드를 지정합니다.

[]string{fiber.MethodGet, fiber.MethodHead}

Default Config

var ConfigDefault = Config{
    Next:         nil,
    Expiration:   1 * time.Minute,
	CacheHeader:  "X-Cache",
    CacheControl: false,
    KeyGenerator: func(c *fiber.Ctx) string {
        return utils.CopyString(c.Path())
    },
    ExpirationGenerator:  nil,
    StoreResponseHeaders: false,
    Storage:              nil,
    MaxBytes:             0,
    Methods: []string{fiber.MethodGet, fiber.MethodHead},
}

Last updated