New creates a new middleware handler
(config ...Config)
| 98 | |
| 99 | // New creates a new middleware handler |
| 100 | func New(config ...Config) fiber.Handler { |
| 101 | // Set default config |
| 102 | cfg := configDefault(config...) |
| 103 | |
| 104 | type evictionCandidate struct { |
| 105 | key string |
| 106 | size uint |
| 107 | exp uint64 |
| 108 | heapIdx int |
| 109 | } |
| 110 | |
| 111 | redactKeys := !cfg.DisableValueRedaction |
| 112 | |
| 113 | maskKey := func(key string) string { |
| 114 | if redactKeys { |
| 115 | return redactedKey |
| 116 | } |
| 117 | return key |
| 118 | } |
| 119 | |
| 120 | // Nothing to cache |
| 121 | if int(cfg.Expiration.Seconds()) < 0 { |
| 122 | return func(c fiber.Ctx) error { |
| 123 | return c.Next() |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // Cache settings |
| 128 | mux := &sync.RWMutex{} |
| 129 | // Create manager to simplify storage operations ( see manager.go ) |
| 130 | manager := newManager(cfg.Storage, redactKeys) |
| 131 | // Create indexed heap for tracking expirations ( see heap.go ) |
| 132 | heap := &indexedHeap{} |
| 133 | // count stored bytes (sizes of response bodies) |
| 134 | var storedBytes uint |
| 135 | // Pool for hex encoding buffers |
| 136 | hexBufPool := &sync.Pool{ |
| 137 | New: func() any { |
| 138 | buf := make([]byte, hexLen) |
| 139 | return &buf |
| 140 | }, |
| 141 | } |
| 142 | hashAuthorization := makeHashAuthFunc(hexBufPool) |
| 143 | buildVaryKey := makeBuildVaryKeyFunc(hexBufPool) |
| 144 | |
| 145 | // Delete key from both manager and storage |
| 146 | deleteKey := func(ctx context.Context, dkey string) error { |
| 147 | if err := manager.del(ctx, dkey); err != nil { |
| 148 | return err |
| 149 | } |
| 150 | // External storage saves body data with different key |
| 151 | if cfg.Storage != nil { |
| 152 | if err := manager.del(ctx, dkey+"_body"); err != nil { |
| 153 | return err |
| 154 | } |
| 155 | } |
| 156 | return nil |
| 157 | } |