A simple, generic lazy-loading library for Go with caching support.
lazy
is a lightweight Go package that provides a flexible, type-safe lazy-loading mechanism with built-in caching. It allows you to defer the execution of a data-fetching function until the data is needed, while caching the result for subsequent calls. The package is designed to be modular, supporting any cache implementation that adheres to the Cache
interface.
- Generic type support for flexible usage
- Configurable caching with custom TTL
- Simple interface for lazy-loaded data fetching
- Context-aware data retrieval
- Minimal dependencies
To install the package, use the following command:
go get github.com/revrost/lazy
package main
import (
"context"
"fmt"
"time"
"github.com/labstack/echo/v4"
"github.com/yourusername/lazy"
)
type InMemoryCache struct {
store map[string]interface{}
}
func (c *InMemoryCache) Get(key string) (interface{}, bool) {
val, ok := c.store[key]
return val, ok
}
func (c *InMemoryCache) Set(key string, value interface{}, ttl time.Duration) {
c.store[key] = value
// In a real implementation, handle TTL with expiration
}
func main() {
// Initialize a simple in-memory cache
cache := &InMemoryCache{store: make(map[string]interface{})}
// Define a fetch function
fetchFunc := func(ctx context.Context) (string, error) {
// Simulate expensive operation
time.Sleep(1 * time.Second)
return "Hello, Lazy!", nil
}
// Create a Lazy instance
lazyLoader := lazy.New(
cache,
lazy.WithKey[string]("greeting"),
lazy.WithTTL[string](5*time.Minute),
lazy.WithFetch[string](fetchFunc),
)
// Use it with context
ctx := context.Background()
data, err := lazyLoader.Get(ctx)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Data:", data) // Output: Data: Hello, Lazy!
// Subsequent calls will use the cached value
data, err = lazyLoader.Get(ctx)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Cached Data:", data) // Output: Cached Data: Hello, Lazy!
}
- Cache Interface: Implement this to use your own caching mechanism.
- Get(key string) (interface{}, bool)
- Set(key string, value interface{}, ttl time.Duration)
- FetchFunc[T]: A function that retrieves the data lazily.
- Lazy[T]: The core struct that handles lazy loading and caching.
- Option[T]: Configuration options like WithKey, WithTTL, and WithFetch.
- WithKey[T](key string): Sets the cache key.
- WithTTL[T](ttl time.Duration): Sets the time-to-live for cached data (default: 10 minutes).
- WithFetch[T](fetch FetchFunc[T]): Sets the data-fetching function.