### Configure Cache TTL Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Shows how to set the Time To Live (TTL) for cached items. A TTL of 0 means permanent cache, while a positive value sets the cache duration. This example sets the TTL to 1 hour. ```go gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ /* Set cache's TTL time: if TTL==0, use permanent cache; if TTL>0, cache's live time is TTL */ TTL: time.Hour, }) ``` -------------------------------- ### Cache Function with Redis Cache Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Illustrates caching function results using Redis as the backend. This approach is suitable for distributed caching but may lead to data loss due to JSON marshaling. The example shows how to configure Redis cache with a key and test its functionality with TTL. ```go var ( // Cacheable Function getUserScoreWithCache = gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ TTL: time.Hour, CacheMap: gofnext.NewCacheRedis("redis-cache-key"), }) ) func TestRedisCacheFuncWithTTL(t *testing.T) { // Execute the function multi times in parallel. for i := 0; i < 10; i++ { score, _ := getUserScoreWithCache(1) if score != 99 { t.Errorf("score should be 99, but get %d", score) } } } ``` -------------------------------- ### Cache Function with Two Parameters and TTL in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Supports caching for functions with two parameters, utilizing a combination of both inputs for cache keys. This example also demonstrates configuring a Time-To-Live (TTL) for cache entries using `gofnext.Config`. The cached results will expire after the specified duration. Requires the 'gofnext' library. ```go package main import ( "context" "fmt" "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string Age int } func getUserScore(ctx context.Context, id int) int { fmt.Printf("Fetching score for user ID %d...\n", id) time.Sleep(10 * time.Millisecond) return 98 + id } func main() { // Cache function with TTL of 1 hour getUserScoreCached := gofnext.CacheFn2(getUserScore, &gofnext.Config{ TTL: time.Hour, }) ctx := context.Background() // First call executes function score1 := getUserScoreCached(ctx, 1) fmt.Printf("User 1 score: %d\n", score1) // Second call with same ID uses cache score2 := getUserScoreCached(ctx, 1) fmt.Printf("User 1 score (cached): %d\n", score2) // Different ID executes function score3 := getUserScoreCached(ctx, 2) fmt.Printf("User 2 score: %d\n", score3) } ``` -------------------------------- ### Cache Method (Factory Mode) using gofnext Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Demonstrates caching a method within a struct using gofnext.CacheFn1Err in a factory pattern. Each instance of the User struct gets its own cached version of the `getUserInfo` method, initialized when the `NewUser` factory function is called. This allows for instance-specific caching. ```go import "github.com/ahuigo/gofnext" type User struct { getUserInfoCached func(uid int) (*User, error) } func NewUser() *User{ u := &User{} u.getUserInfoCached = gofnext.CacheFn1Err(u.getUserInfo) return u } // Origin method func (u *User) getUserInfo(uid int) (*User, error) { fmt.Printf("mock data: uid=%d\n", uid) return &User{}, nil } // Cached method access (assuming GetUserInfo calls u.getUserInfoCached) // func (u *User) GetUserInfo(uid int) (*User, error) { // return u.getUserInfoCached(uid) // } ``` -------------------------------- ### Cache Function with 1 Parameter (No Error) using gofnext Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Illustrates caching a function that accepts one integer parameter and returns a UserInfo struct without an error. The gofnext.CacheFn1 decorator is applied. The example shows parallel execution to test the cache's effectiveness for a function with a single argument. ```go import "github.com/ahuigo/gofnext" import ( "fmt" "time" ) type UserInfo struct { Name string Age int } func getUserNoError(age int) (UserInfo) { time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Alex", Age: age} } var ( // Cacheable Function with 1 param and no error getUserInfoFromDbNil= gofnext.CacheFn1(getUserNoError) ) func TestCacheFuncNil(t *testing.T) { // Execute the function multi times in parallel. times := 10 parallelCall(func() { userinfo := getUserInfoFromDbNil(20) fmt.Println(userinfo) }, times) } ``` -------------------------------- ### Cache Fibonacci Function using gofnext.CacheFn1 Source: https://github.com/ahuigo/gofnext/blob/main/readme.md This example demonstrates caching a recursive Fibonacci function using gofnext's CacheFn1 decorator. It caches results based on the single integer argument, significantly speeding up subsequent calls with the same input. The function signature is `func(int) int`. ```go package main import "fmt" import "github.com/ahuigo/gofnext" func main() { var fib func(int) int fib = func(x int) int { fmt.Printf("call arg:%d\n", x) if x <= 1 { return x } else { return fib(x-1) + fib(x-2) } } fib = gofnext.CacheFn1(fib) fmt.Println(fib(5)) fmt.Println(fib(6)) } ``` -------------------------------- ### Cache Function with 2 Parameters (with Error) using gofnext Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Demonstrates caching a function that takes two parameters (context and an integer ID) and returns an integer score and an error. The gofnext.CacheFn2Err decorator is used with a configured TTL. The example verifies that the underlying function is called only once for each unique parameter set, even with parallel requests. ```go import ( "context" "errors" "fmt" "github.com/ahuigo/gofnext" "time" ) func TestCacheFuncWith2Param(t *testing.T) { // Original function executeCount := 0 getUserScore := func(c context.Context, id int) (int, error) { executeCount++ fmt.Println("select score from db where id=", id, time.Now()) time.Sleep(10 * time.Millisecond) return 98 + id, errors.New("db error") } // Cacheable Function getUserScoreWithCache := gofnext.CacheFn2Err(getUserScore, &gofnext.Config{ TTL: time.Hour, }) // getFunc can only accept 2 parameter // Execute the function multi times in parallel. ctx := context.Background() parallelCall(func() { score, _ := getUserScoreWithCache(ctx, 1) if score != 99 { t.Errorf("score should be 99, but get %d", score) } getUserScoreWithCache(ctx, 2) getUserScoreWithCache(ctx, 3) }, 10) if executeCount != 3 { t.Errorf("executeCount should be 3, but get %d", executeCount) } } ``` -------------------------------- ### Cache Method in Singleton Pattern (Go) Source: https://context7.com/ahuigo/gofnext/llms.txt Demonstrates how to apply caching to struct methods using the singleton initialization pattern with gofnext. This ensures that a method's result is cached and only recomputed when necessary, improving performance. It uses `sync.Once` for thread-safe initialization of the cached function. ```go package main import ( "fmt" "sync" "github.com/ahuigo/gofnext" ) type User struct { ID int Name string } type UserService struct{} var ( getUserInfoCached func(uid int) (*User, error) once sync.Once ) func NewUserService() *UserService { u := &UserService{} once.Do(func() { // Initialize cached method once getUserInfoCached = gofnext.CacheFn1Err(u.getUserInfo) }) return u } // Public cached method func (u *UserService) GetUserInfo(uid int) (*User, error) { return getUserInfoCached(uid) } // Private implementation func (u *UserService) getUserInfo(uid int) (*User, error) { fmt.Printf("Fetching user %d from database...\n", uid) return &User{ID: uid, Name: "User"}, nil } func main() { service := NewUserService() // First call executes method user1, _ := service.GetUserInfo(1) fmt.Printf("User: %v\n", user1) // Second call uses cache user2, _ := service.GetUserInfo(1) fmt.Printf("User (cached): %v\n", user2) } ``` -------------------------------- ### Set Redis Cache Connection Options Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Demonstrates various ways to configure the Redis connection for the cache decorator, including default settings, specifying the address, and using redis-go options. ```go // method 1: by default: localhost:6379 cache := gofnext.NewCacheRedis("redis-cache-key") // method 2: set redis addr cache.SetRedisAddr("192.168.1.1:6379") // method 3: set redis options cache.SetRedisOpts(&redis.Options{ Addr: "localhost:6379", }) // method 4: set redis universal options cache.SetRedisUniversalOpts(&redis.UniversalOptions{ Addrs: []string{"localhost:6379"}, }) ``` -------------------------------- ### Custom Hash Key Function for Cache Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Shows how to define a custom function for generating cache keys. This is useful when the default hashing mechanism is insufficient. The custom function must ensure that unique keys are generated for distinct inputs. ```go // hash key function hashKeyFunc := func(keys ...any) []byte{ user := keys[0].(*UserInfo) flag := keys[1].(bool) return []byte(fmt.Sprintf("user:%d,flag:%t", user.id, flag)) } // Cacheable Function getUserScoreWithCache := gofnext.CacheFn2Err(getUserScore, &gofnext.Config{ HashKeyFunc: hashKeyFunc, }) ``` -------------------------------- ### Use Redis Cache Backend in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Configures and uses Redis as a distributed cache backend for Go functions. This approach allows multiple application instances to share a common cache. It requires the 'github.com/go-redis/redis' library and a running Redis server. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" "github.com/go-redis/redis" ) func getInventory(productID int) int { fmt.Printf("Fetching inventory for product %d...\n", productID) return 100 + productID } func main() { // Configure Redis cache cacheMap := gofnext.NewCacheRedis("inventory-cache") cacheMap.SetRedisOpts(&redis.Options{ Addr: "localhost:6379", DB: 0, }) // Create cached function with Redis backend getInventoryCached := gofnext.CacheFn1(getInventory, &gofnext.Config{ TTL: time.Hour, CacheMap: cacheMap, }) // First call stores in Redis inventory1 := getInventoryCached(1) fmt.Printf("Inventory: %d\n", inventory1) // Subsequent calls read from Redis inventory2 := getInventoryCached(1) fmt.Printf("Inventory (from Redis): %d\n", inventory2) } ``` -------------------------------- ### Use LRU Cache with Max Size in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Demonstrates using a Least Recently Used (LRU) cache with a maximum size limit with the 'gofnext' library. This is useful for controlling memory consumption by evicting the least recently accessed items when the cache reaches its capacity. It requires 'gofnext' and 'time'. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) func getDataByID(id int) string { fmt.Printf("Fetching data for ID %d...\n", id) return fmt.Sprintf("Data-%d", id) } func main() { // LRU cache with max 2 entries getDataCached := gofnext.CacheFn1(getDataByID, &gofnext.Config{ TTL: time.Hour, CacheMap: gofnext.NewCacheLru(2), }) // Cache IDs 1 and 2 data1 := getDataCached(1) fmt.Println(data1) data2 := getDataCached(2) fmt.Println(data2) // ID 3 evicts ID 1 (least recently used) data3 := getDataCached(3) fmt.Println(data3) // ID 1 must be fetched again (was evicted) data1Again := getDataCached(1) fmt.Println(data1Again) // ID 2 was evicted by ID 1 data2Again := getDataCached(2) fmt.Println(data2Again) } ``` -------------------------------- ### Hash Pointer Address for Cache Key Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Demonstrates how to use the memory address of a pointer as the cache key instead of its value. This is controlled by the `HashKeyPointerAddr` option in the `gofnext.Config`. ```go getUserScoreWithCache := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ HashKeyPointerAddr: true, }) ``` -------------------------------- ### Cache Method (Singleton Mode) using gofnext Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Shows how to cache a method of a struct using gofnext.CacheFn1Err in a singleton pattern. The cached function is initialized once using sync.Once, ensuring that the original method is called only when necessary. This is suitable for methods that should have a single cached instance. ```go import ( "fmt" "sync" "github.com/ahuigo/gofnext" ) type User struct {} var ( getUserInfoCached func(uid int) (*User, error) once sync.Once ) func NewUser() *User { u := &User{} once.Do(func() { // use cache decorator getUserInfoCached = gofnext.CacheFn1Err(u.getUserInfo) }) return u } // Cached method func (u *User) GetUserInfo(uid int) (*User, error) { return getUserInfoCached(uid) } // Origin method func (u *User) getUserInfo(uid int) (*User, error) { fmt.Printf("mock data: uid=%d\n", uid) return &User{}, nil } ``` -------------------------------- ### Cache Recursive Function (Fibonacci) Source: https://context7.com/ahuigo/gofnext/llms.txt Demonstrates caching recursive functions for dramatic performance improvements. By caching intermediate results, the complexity is reduced significantly. ```APIDOC ## Cache Recursive Function (Fibonacci) ### Description Demonstrates caching recursive functions for dramatic performance improvements. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```go package main import ( "fmt" "github.com/ahuigo/gofnext" ) func main() { var fib func(int) int // Define recursive fibonacci function fib = func(x int) int { fmt.Printf("Computing fib(%d)\n", x) if x <= 1 { return x } return fib(x-1) + fib(x-2) } // Wrap with cache decorator fib = gofnext.CacheFn1(fib) // First call computes fib(0) through fib(5) result1 := fib(5) fmt.Printf("fib(5) = %d\n", result1) // Second call reuses cached values, only computes fib(6) result2 := fib(6) fmt.Printf("fib(6) = %d\n", result2) } ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Reuse Expired Cache with ReuseTTL (Go) Source: https://context7.com/ahuigo/gofnext/llms.txt Illustrates how to use gofnext's `ReuseTTL` option to immediately return stale cache data while updating it asynchronously in the background. This is useful for expensive operations where serving slightly outdated data quickly is preferable to waiting for a fresh computation. The cache is configured with a short `TTL` and a longer `ReuseTTL`. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) func getExpensiveData(id int) string { fmt.Printf("Expensive computation for ID %d...\n", id) time.Sleep(100 * time.Millisecond) // Simulate slow operation return fmt.Sprintf("Data-%d-v%d", id, time.Now().Unix()) } func main() { getCached := gofnext.CacheFn1(getExpensiveData, &gofnext.Config{ TTL: 50 * time.Millisecond, // Cache expires after 50ms ReuseTTL: 100 * time.Millisecond, // Reuse stale cache for 100ms more }) // First call caches result data1 := getCached(1) fmt.Printf("Data: %s\n", data1) // After TTL but within ReuseTTL: returns stale cache immediately // and triggers async update time.Sleep(60 * time.Millisecond) data2 := getCached(1) fmt.Printf("Data (stale but fast): %s\n", data2) // Wait for async update to complete time.Sleep(150 * time.Millisecond) data3 := getCached(1) fmt.Printf("Data (updated): %s\n", data3) } ``` -------------------------------- ### Configure Cache Time-to-Live (TTL) in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Demonstrates how to configure the Time-to-Live (TTL) for cached values using the 'gofnext' library. This setting determines how long a cached result remains valid before the original function is re-executed. It requires the 'gofnext' and 'time' packages. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) func getPrice(productID int) float64 { fmt.Printf("Fetching price for product %d...\n", productID) return 99.99 } func main() { // Cache with 5-second TTL getPriceCached := gofnext.CacheFn1(getPrice, &gofnext.Config{ TTL: 5 * time.Second, }) // First call caches result price1 := getPriceCached(1) fmt.Printf("Price: $%.2f\n", price1) // Within TTL, uses cache time.Sleep(2 * time.Second) price2 := getPriceCached(1) fmt.Printf("Price (cached): $%.2f\n", price2) // After TTL expires, re-executes function time.Sleep(4 * time.Second) price3 := getPriceCached(1) fmt.Printf("Price (refreshed): $%.2f\n", price3) } ``` -------------------------------- ### Cache Function with >3 Parameters using gofnext Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Explains how to cache a function with more than three parameters by wrapping it. The original function `fn` is wrapped into `fnWrap` which takes a struct `Stu` as a single parameter. This `fnWrap` is then cached using gofnext.CacheFn1, and a final wrapper `fnCached` is created to match the original function signature. This approach effectively caches functions with numerous arguments. ```go import "github.com/ahuigo/gofnext" type Stu struct { name string age int gender int } // Test Count // if executeCount != 2 { // t.Errorf("executeCount should be 2, but get %d", executeCount) // } func TestCacheFuncWithMoreParam(t *testing.T) { executeCount := 0 // Original function fn := func(name string, age, gender int) int { executeCount++ // select score from db where name=name and age=age and gender=gender switch name { case "Alex": return 10 default: return 30 } } // Convert to extra parameters to a single parameter(2 prameters is ok) fnWrap := func(arg Stu) int { return fn(arg.name, arg.age, arg.gender) } // Cacheable Function fnCachedInner := gofnext.CacheFn1(fnWrap) fnCached := func(name string, age, gender int) int { return fnCachedInner(Stu{name, age, gender}) } // Execute the function multi times in parallel. parallelCall(func() { score := fnCached("Alex", 20, 1) if score != 10 { t.Errorf("score should be 10, but get %d", score) } fnCached("Jhon", 21, 0) fnCached("Alex", 20, 1) }, 10) // Test Count if executeCount != 2 { t.Errorf("executeCount should be 2, but get %d", executeCount) } } ``` -------------------------------- ### Cache Recursive Fibonacci Function in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Demonstrates caching for recursive functions like Fibonacci, significantly improving performance by storing intermediate results. The `CacheFn1` decorator is applied to the recursive function itself, ensuring that each computation for a given input is performed only once. Requires the 'gofnext' library. ```go package main import ( "fmt" "github.com/ahuigo/gofnext" ) func main() { var fib func(int) int // Define recursive fibonacci function fib = func(x int) int { fmt.Printf("Computing fib(%d)\n", x) if x <= 1 { return x } return fib(x-1) + fib(x-2) } // Wrap with cache decorator fib = gofnext.CacheFn1(fib) // First call computes fib(0) through fib(5) result1 := fib(5) fmt.Printf("fib(5) = %d\n", result1) // Second call reuses cached values, only computes fib(6) result2 := fib(6) fmt.Printf("fib(6) = %d\n", result2) } ``` -------------------------------- ### Cache Function with LRU Cache Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Demonstrates caching a function's results using an LRU (Least Recently Used) cache. This is useful for in-memory caching with a specified size limit. The `CacheFn1Err` decorator applies the caching logic to a function that takes one argument and returns a value and an error. ```go executeCount := 0 maxCacheSize := 2 var getUserScore = func(more int) (int, error) { executeCount++ return 98 + more, errors.New("db error") } // Cacheable Function var getUserScoreFromDbWithLruCache = gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ TTL: time.Hour, CacheMap: gofnext.NewCacheLru(maxCacheSize), }) ``` -------------------------------- ### Cache Function with Three Parameters in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Caches functions that accept exactly three parameters. It generates cache keys based on all provided parameter values. This function requires the 'gofnext' library. It takes the original function and an optional configuration as input. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) func sum(a, b, c int) int { fmt.Printf("Computing %d + %d + %d\n", a, b, c) time.Sleep(10 * time.Millisecond) return a + b + c } func main() { sumCached := gofnext.CacheFn3(sum, &gofnext.Config{ TTL: time.Hour, }) // First call executes function result1 := sumCached(1, 3, 5) fmt.Printf("Result: %d\n", result1) // Same parameters use cache result2 := sumCached(1, 3, 5) fmt.Printf("Result (cached): %d\n", result2) // Different parameters execute function result3 := sumCached(1, 3, 6) fmt.Printf("Result: %d\n", result3) } ``` -------------------------------- ### Cache Function with 0 Parameters using gofnext Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Demonstrates caching a function that takes no parameters and returns a UserInfo and an error. The gofnext.CacheFn0Err decorator is used to cache the results, and parallel calls are made to verify its behavior. This is useful for functions that perform expensive operations like database queries. ```go package examples import "github.com/ahuigo/gofnext" import ( "errors" "fmt" "time" ) type UserInfo struct { Name string Age int } func getUserAnonymouse() (UserInfo, error) { fmt.Println("select * from db limit 1", time.Now()) time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Anonymous", Age: 9}, errors.New("db error") } var ( // Cacheable Function getUserInfoFromDbWithCache = gofnext.CacheFn0Err(getUserAnonymouse) ) func TestCacheFuncWithNoParam(t *testing.T) { // Execute the function multi times in parallel. times := 10 parallelCall(func() { userinfo, err := getUserInfoFromDbWithCache() fmt.Println(userinfo, err) }, times) } ``` -------------------------------- ### Hash Pointer Address vs Value in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Controls how pointer parameters are handled by the cache: by their memory address or by the value they point to. The default behavior is to hash the value. Setting `HashKeyPointerAddr` to `true` will hash the memory address instead. This affects cache hits/misses when multiple pointers point to the same data or when identical data is represented by different pointers. Requires gofnext library. ```go package main import ( "fmt" "github.com/ahuigo/gofnext" ) type Config struct { value int } func processConfig(cfg *Config) string { fmt.Printf("Processing config with value %d...\n", cfg.value) return fmt.Sprintf("Processed-%d", cfg.value) } func main() { // Hash by pointer address (default: false, hashes value) processCached := gofnext.CacheFn1(processConfig, &gofnext.Config{ HashKeyPointerAddr: true, }) cfg1 := &Config{value: 10} cfg2 := &Config{value: 10} // Same value, different address // First call caches by pointer address result1 := processCached(cfg1) fmt.Printf("Result: %s\n", result1) // Different pointer address, so cache miss (even though value is same) result2 := processCached(cfg2) fmt.Printf("Result: %s\n", result2) // Same pointer, cache hit result3 := processCached(cfg1) fmt.Printf("Result (cached): %s\n", result3) } ``` -------------------------------- ### Configure Redis Cache Key Length Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Provides a method to limit the length of Redis keys generated by the cache decorator. This helps in managing key size and potential issues in Redis. ```go cacheMap := gofnext.NewCacheRedis("redis-cache-key").SetMaxHashKeyLen(256); ``` -------------------------------- ### Cache Function with Two Parameters Source: https://context7.com/ahuigo/gofnext/llms.txt Supports functions with two parameters, caching based on the combination of both values. Configuration options like TTL can be applied. ```APIDOC ## Cache Function with Two Parameters ### Description Supports functions with two parameters, caching based on the combination of both values. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```go package main import ( "context" "fmt" time "time" "github.com/ahuigo/gofnext" ) func getUserScore(ctx context.Context, id int) int { fmt.Printf("Fetching score for user ID %d...\n", id) time.Sleep(10 * time.Millisecond) return 98 + id } func main() { // Cache function with TTL of 1 hour getUserScoreCached := gofnext.CacheFn2(getUserScore, &gofnext.Config{ TTL: time.Hour, }) ctx := context.Background() // First call executes function score1 := getUserScoreCached(ctx, 1) fmt.Printf("User 1 score: %d\n", score1) // Second call with same ID uses cache score2 := getUserScoreCached(ctx, 1) fmt.Printf("User 1 score (cached): %d\n", score2) // Different ID executes function score3 := getUserScoreCached(ctx, 2) fmt.Printf("User 2 score: %d\n", score3) } ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Cache Function with Zero Parameters in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Wraps a function with no parameters to cache its return value. Subsequent calls with the same function signature will return the cached result, avoiding re-execution. This is useful for expensive, non-changing computations. Requires the 'gofnext' library. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string Age int } func getUser() UserInfo { fmt.Println("Fetching user from database...") time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Alex", Age: 20} } func main() { // Create cached version of function getUserCached := gofnext.CacheFn0(getUser) // First call executes function user1 := getUserCached() // prints "Fetching user from database..." fmt.Println(user1) // Second call returns cached result user2 := getUserCached() // no print, uses cache fmt.Println(user2) } ``` -------------------------------- ### Configure Error Caching in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Shows how to configure error caching using the 'ErrTTL' option in 'gofnext.Config'. This prevents repeatedly executing a function that returns an error within a specified duration. It requires the 'gofnext', 'errors', and 'time' packages. ```go package main import ( "errors" "fmt" "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string Age int } func validateUser(age int) (UserInfo, error) { fmt.Printf("Validating age %d...\n", age) if age <= 0 { return UserInfo{}, errors.New("invalid age") } return UserInfo{Name: "Valid User", Age: age}, nil } func main() { // Cache errors for 1 hour to prevent repeated validation attempts validateCached := gofnext.CacheFn1Err(validateUser, &gofnext.Config{ ErrTTL: time.Hour, }) // First error call caches the error _, err1 := validateCached(0) fmt.Printf("Error: %v\n", err1) // Subsequent calls return cached error without re-executing _, err2 := validateCached(0) fmt.Printf("Error (cached): %v\n", err2) // Valid input executes and caches successfully user, err3 := validateCached(25) fmt.Printf("User: %v, Error: %v\n", user, err3) } ``` -------------------------------- ### Cache Function with One Parameter in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Wraps a function with a single parameter, caching results based on the input value. Each unique parameter value will have its own cache entry, preventing redundant computations for identical inputs. This enhances performance for functions with repeated arguments. Requires the 'gofnext' library. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string Age int } func getUserByAge(age int) UserInfo { fmt.Printf("Fetching user with age %d from database...\n", age) time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Alex", Age: age} } func main() { getUserCached := gofnext.CacheFn1(getUserByAge) // First call with age=20 executes function user1 := getUserCached(20) fmt.Println(user1) // Second call with age=20 uses cache user2 := getUserCached(20) fmt.Println(user2) // Call with age=25 executes function (different parameter) user3 := getUserCached(25) fmt.Println(user3) } ``` -------------------------------- ### Cache Function with Zero Parameters Source: https://context7.com/ahuigo/gofnext/llms.txt Wraps a function with no parameters to cache its return value. Subsequent calls return the cached result without re-executing the function. ```APIDOC ## Cache Function with Zero Parameters ### Description Wraps a function with no parameters to cache its return value. Subsequent calls return the cached result without re-executing the function. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```go package main import ( "fmt" time "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string; Age int } func getUser() UserInfo { fmt.Println("Fetching user from database...") time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Alex", Age: 20} } func main() { // Create cached version of function getUserCached := gofnext.CacheFn0(getUser) // First call executes function user1 := getUserCached() // prints "Fetching user from database..." fmt.Println(user1) // Second call returns cached result user2 := getUserCached() // no print, uses cache fmt.Println(user2) } ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Define Custom Hash Key Function in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Allows defining custom logic for generating cache keys based on function parameters, overriding the default hashing mechanism. This is useful for complex parameter types or when specific fields should determine cache uniqueness. Requires gofnext library. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) type User struct { id int name string } func getUserPermissions(user *User, adminMode bool) []string { fmt.Printf("Fetching permissions for user %d (admin: %v)... ", user.id, adminMode) return []string{"read", "write"} } func main() { // Custom hash function uses only user ID and admin flag hashKeyFunc := func(keys ...any) []byte { user := keys[0].(*User) flag := keys[1].(bool) return []byte(fmt.Sprintf("user:%d,admin:%t", user.id, flag)) } getPermsCached := gofnext.CacheFn2(getUserPermissions, &gofnext.Config{ HashKeyFunc: hashKeyFunc, }) user1 := &User{id: 1, name: "Alice"} user2 := &User{id: 1, name: "Alice Modified"} // Same ID as user1 // First call caches result perms1 := getPermsCached(user1, false) fmt.Println(perms1) // Uses cache because custom hash only checks ID (ignores name) perms2 := getPermsCached(user2, false) fmt.Println(perms2) // Different admin flag creates new cache entry perms3 := getPermsCached(user1, true) fmt.Println(perms3) } ``` -------------------------------- ### Cache Function with More Than Three Parameters in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Caches functions with more than three parameters using a struct wrapper pattern. This approach involves creating a wrapper function that accepts a single struct containing all parameters and then caching this wrapper. It relies on the 'gofnext' library. ```go package main import ( "fmt" "github.com/ahuigo/gofnext" ) type StudentQuery struct { name string age int gender int height int } func getStudentScore(name string, age, gender, height int) int { fmt.Printf("Querying score for %s...\n", name) switch name { case "Alex": return 10 default: return 30 } } func main() { // Wrap original function to accept single struct parameter fnWrap := func(arg StudentQuery) int { return getStudentScore(arg.name, arg.age, arg.gender, arg.height) } // Cache the wrapper function fnCachedInner := gofnext.CacheFn1(fnWrap) // Create final function with original signature getScoreCached := func(name string, age, gender, height int) int { return fnCachedInner(StudentQuery{name, age, gender, height}) } // First call executes function score1 := getScoreCached("Alex", 20, 1, 160) fmt.Printf("Score: %d\n", score1) // Same parameters use cache score2 := getScoreCached("Alex", 20, 1, 160) fmt.Printf("Score (cached): %d\n", score2) // Different name executes function score3 := getScoreCached("John", 21, 0, 160) fmt.Printf("Score: %d\n", score3) } ``` -------------------------------- ### Configure Redis Max Key Length in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Limits the maximum length of Redis cache keys by hashing longer keys, preventing potential memory issues in Redis. This is useful when dealing with functions that might generate very long input parameters. It uses the gofnext library's caching capabilities. ```go package main import ( "fmt" "time" "github.com/ahuigo/gofnext" ) func processComplexQuery(query string) string { fmt.Printf("Processing query (length %d)... ", len(query)) return "result" } func main() { // Limit Redis key length to 256 chars (hashes longer keys) cacheMap := gofnext.NewCacheRedis("query-cache").SetMaxHashKeyLen(256) processCached := gofnext.CacheFn1(processComplexQuery, &gofnext.Config{ TTL: time.Minute * 30, CacheMap: cacheMap, }) // Long query string will be hashed before storage longQuery := "SELECT * FROM users WHERE " + string(make([]byte, 500)) result := processCached(longQuery) fmt.Printf("Result: %s\n", result) // Same query uses hashed cache key result2 := processCached(longQuery) fmt.Printf("Result (cached): %s\n", result2) } ``` -------------------------------- ### Cache Function with One Parameter Source: https://context7.com/ahuigo/gofnext/llms.txt Caches function results based on the input parameter value. Each unique parameter creates a separate cache entry. ```APIDOC ## Cache Function with One Parameter ### Description Caches function results based on the input parameter value. Each unique parameter creates a separate cache entry. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```go package main import ( "fmt" time "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string; Age int } func getUserByAge(age int) UserInfo { fmt.Printf("Fetching user with age %d from database...\n", age) time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Alex", Age: age} } func main() { getUserCached := gofnext.CacheFn1(getUserByAge) // First call with age=20 executes function user1 := getUserCached(20) fmt.Println(user1) // Second call with age=20 uses cache user2 := getUserCached(20) fmt.Println(user2) // Call with age=25 executes function (different parameter) user3 := getUserCached(25) fmt.Println(user3) } ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Cache Function with Zero Parameters and Error Return Source: https://context7.com/ahuigo/gofnext/llms.txt Caches functions returning a value and error. By default, errors are not cached, meaning each call will execute the function if it returns an error. ```APIDOC ## Cache Function with Zero Parameters and Error Return ### Description Caches functions returning a value and error. By default, errors are not cached. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```go package main import ( "errors" "fmt" time "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string; Age int } func getUserWithErr() (UserInfo, error) { fmt.Println("Querying database...") time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Anonymous", Age: 9}, errors.New("db error") } func main() { // Cache function with error return getUserCached := gofnext.CacheFn0Err(getUserWithErr) // Each call executes function because errors aren't cached by default for i := 0; i < 3; i++ { user, err := getUserCached() fmt.Printf("Call %d: %v, error: %v\n", i+1, user, err) } } ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Configure Error Cache TTL Source: https://github.com/ahuigo/gofnext/blob/main/readme.md Explains how to control the caching duration for errors returned by a decorated function. By default, errors are not cached. Setting `ErrTTL` to a positive duration enables error caching for that specified period. ```go gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ /* Set error cache's TTL time: if ErrTTL<=0, do not cache error; if ErrTTL>0, error cache's live time is ErrTTL; */ ErrTTL: 0, // Do not cache error(default:0) ErrTTL: time.Seconds * 60, // error cache's live time is 60s }) ``` -------------------------------- ### Cache Function with Zero Parameters and Error Return in Go Source: https://context7.com/ahuigo/gofnext/llms.txt Caches functions that return a value and an error. By default, errors are not cached, meaning the function will re-execute on each call if it returns an error. This decorator is suitable for functions where error conditions should not be memoized. Requires the 'gofnext' library. ```go package main import ( "errors" "fmt" "time" "github.com/ahuigo/gofnext" ) type UserInfo struct { Name string Age int } func getUserWithErr() (UserInfo, error) { fmt.Println("Querying database...") time.Sleep(10 * time.Millisecond) return UserInfo{Name: "Anonymous", Age: 9}, errors.New("db error") } func main() { // Cache function with error return getUserCached := gofnext.CacheFn0Err(getUserWithErr) // Each call executes function because errors aren't cached by default for i := 0; i < 3; i++ { user, err := getUserCached() fmt.Printf("Call %d: %v, error: %v\n", i+1, user, err) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.