middlewares

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CacheMiddleware = func(cache Cacher, ttl time.Duration, logger requests.Logger) requests.Middleware {
	return func(next requests.MiddlewareHandlerFunc) requests.MiddlewareHandlerFunc {
		return func(req *http.Request) (*http.Response, error) {

			if req.Method != http.MethodGet {
				return next(req)
			}

			cacheKey := generateCacheKey(req)

			cachedData, ok := cache.Get(cacheKey)
			if ok {
				logger.Debugf("Cache hit", map[string]interface{}{
					"url": req.URL.String(),
					"key": cacheKey,
				})

				return buildResponseFromCache(cachedData)
			}

			resp, err := next(req)
			if err != nil {
				return nil, err
			}

			if resp.StatusCode == http.StatusOK {
				if data, err := cacheResponse(resp); err == nil {

					cache.Set(cacheKey, data, ttl)
					logger.Debugf("Cached response", map[string]interface{}{
						"url": req.URL.String(),
						"key": cacheKey,
					})
				}
			}

			return resp, nil
		}
	}
}

CacheMiddleware is the middleware for the cache

View Source
var CookieMiddleware = func(cookies []*http.Cookie) requests.Middleware {
	return func(next requests.MiddlewareHandlerFunc) requests.MiddlewareHandlerFunc {
		return func(req *http.Request) (*http.Response, error) {
			for _, cookie := range cookies {
				req.AddCookie(cookie)
			}
			return next(req)
		}
	}
}
View Source
var HeaderMiddleware = func(headers http.Header) requests.Middleware {
	return func(next requests.MiddlewareHandlerFunc) requests.MiddlewareHandlerFunc {
		return func(req *http.Request) (*http.Response, error) {
			for key, values := range headers {
				for _, value := range values {
					req.Header.Add(key, value)
				}
			}
			return next(req)
		}
	}
}

Functions

This section is empty.

Types

type CachedResponse

type CachedResponse struct {
	Status     string
	StatusCode int
	Headers    http.Header
	Body       []byte
}

CachedResponse

type Cacher

type Cacher interface {
	Get(key string) ([]byte, bool)
	Set(key string, value []byte, ttl time.Duration)
	Delete(key string)
}

Cacher is the interface for the cache

type Duration

type Duration int64

type MemoryCache

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache

func NewMemoryCache

func NewMemoryCache() *MemoryCache

NewMemoryCache

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(key string)

Delete cache item

func (*MemoryCache) Get

func (c *MemoryCache) Get(key string) ([]byte, bool)

Get cache item

func (*MemoryCache) Set

func (c *MemoryCache) Set(key string, value []byte, ttl time.Duration)

Set cache item

Jump to

Keyboard shortcuts

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