apicache

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2024 License: MIT Imports: 14 Imported by: 0

README

api-cache

api-cache is a reusable Go package for managing Redis cache for HTTP routes.

Installation

go get github.com/Chahine-tech/api-cache

Usage

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
    "github.com/Chahine-tech/api-cache"
    "os"
)

func main() {
    // Set environment variables for testing
    os.Setenv("APICACHE_EXPIRATION", "3600") // 1 hour in seconds
    os.Setenv("APICACHE_PREFIX", "myprefix:")

    // Create a new Redis client
    redisClient := apicache.NewRedisClient("localhost:6379", "", 0)

    // Create an ApiCache instance using environment-based configuration
    cache := apicache.NewApiCache(redisClient, true) // Use true to enable environment-based config

    // Example HTTP request to build the cache key
    req, _ := http.NewRequest("GET", "http://example.com/resource?id=123", nil)

    // Set a value in the cache
    err := cache.SetCache(req, map[string]interface{}{
        "data": "example data",
        "id":   123,
    })
    if err != nil {
        log.Fatalf("Failed to set cache: %v", err)
    }

    // Get a value from the cache
    cachedData, err := cache.GetCache(req)
    if err != nil {
        log.Fatalf("Failed to get cache: %v", err)
    }

    if cachedData != nil {
        fmt.Printf("Cached data: %v\n", cachedData)
    } else {
        fmt.Println("No cached data for this key.")
    }

    // Set up an HTTP server and use CacheMiddleware
    mux := http.NewServeMux()
    // Use the CacheMiddleware for the /resource route
    mux.Handle("/resource", apicache.CacheMiddleware(cache, 24*time.Hour)(http.HandlerFunc(resourceHandler)))

    // Start the HTTP server
    log.Println("Starting server on :8080")
    if err := http.ListenAndServe(":8080", mux); err != nil {
        log.Fatalf("Server failed to start: %v", err)
    }
}

func resourceHandler(w http.ResponseWriter, r *http.Request) {
    // Handle the request and send a response
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte(`{"message": "Hello, World!"}`))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CacheMiddleware

func CacheMiddleware(apiCache *ApiCache, ttl time.Duration) func(http.Handler) http.Handler

CacheMiddleware is a middleware that caches GET requests

func NewRedisClient

func NewRedisClient(addr, password string, db int) *redis.Client

NewRedisClient creates a new Redis client

Types

type ApiCache

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

ApiCache structure

func NewApiCache

func NewApiCache(redisClient *redis.Client, useEnv bool, config ...Config) *ApiCache

NewApiCache creates a new ApiCache instance with optional environment-based configuration

func (*ApiCache) GetCache

func (c *ApiCache) GetCache(req *http.Request) (interface{}, error)

GetCache retrieves data from the cache for a given request

func (*ApiCache) InvalidateCache

func (c *ApiCache) InvalidateCache(req *http.Request) (bool, error)

InvalidateCache invalidates the cache for a given request

func (*ApiCache) SetCache

func (c *ApiCache) SetCache(req *http.Request, data interface{}) (bool, error)

SetCache stores data in the cache for a given request

type Config

type Config struct {
	Expiration time.Duration
	Prefix     string
	TTLs       []EndpointTTL
}

Config holds the configuration for ApiCache

func LoadConfigFromEnv

func LoadConfigFromEnv() Config

LoadConfigFromEnv loads configuration from environment variables

type EndpointTTL

type EndpointTTL struct {
	Path   string
	Method string
	TTL    time.Duration
}

EndpointTTL holds the Time-To-Live configuration for specific endpoints

Jump to

Keyboard shortcuts

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