Go Fiber 한글 공식 문서
  • 🙇‍♀️안녕하세요
  • 🏠Home
    • 👋Welcome
    • 📁API
      • 📦Fiber
      • 🚀App
      • 🧠Ctx
      • 📋Constants
      • 🌎Client
      • 📃Log
      • 🧬Middleware
        • Adaptor
        • BasicAuth
        • Cache
        • Compress
        • CORS
        • CSRF
        • EarlyData
        • Encrypt Cookie
        • EnvVar
        • ETag
        • ExpVar
        • Favicon
        • FileSystem
        • Health Check
        • Helmet
        • Idempotency
        • Keyauth
        • Limiter
        • Logger
        • Monitor
        • Pprof
        • Proxy
        • Recover
        • Redirect
        • RequestID
        • Rewrite
        • Session
        • Skip
        • Timeout
    • 📁Guide
      • 🔌Routing
      • 🎭Grouping
      • 📝Templates
      • 🐛Error Handling
      • 🔎Validation
      • 🎣Hooks
      • ⚡Make Fiber Faster
    • 📁Extra
      • 🤔FAQ
      • 📊Benchmarks
  • 🧩Extra
    • 🧬Contrip
      • 👋Welcome
      • Casbin
      • Fgprof
      • Fiberi18n
      • Fibernewrelic
      • Fibersentry
      • Fiberzap
      • Fiberzerolog
      • JWT
      • LoadShed
      • Opafiber
      • Otelfiber
        • Example
      • Paseto
      • README
      • Swagger
      • Websocket
    • 📦Storage
      • 👋Welcome
      • ArangoDB
      • Azure Blob
      • Badger
      • Bbolt
      • Coherence
      • Couchbase
      • DynamoDB
      • Etcd
      • Memcache
      • Memory
      • Minio
      • MongoDB
      • MSSQL
      • MySQL
      • Nats
      • Pebble
      • Postgres
      • Redis
      • Ristretto
      • Rueidis
      • S3
      • ScyllaDb
      • SQLite3
    • 📃Template
      • 👋Welcome
      • Ace
      • Amber
      • Django
      • Handlebars
      • HTML
        • Golang Templates Cheatsheet
      • Jet
      • Mustache
      • Pug
      • Slim
Powered by GitBook
On this page
  • Signatures
  • Examples
  • Config
  • Default Config
  1. Home
  2. API
  3. Middleware

Cache

PreviousBasicAuthNextCompress

Last updated 1 year ago


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

요청 지시문 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},
}
🏠
📁
🧬
Fiber
@codemicro