This page is generated from the following source files:
The gofnext library requires Go 1.21.1 or later as specified in the go.mod:3 file. The library has minimal dependencies, primarily relying on github.com/go-redis/redis for optional Redis-based caching and github.com/vmihailenco/msgpack/v5 for serialization (go.mod:6-L8).
| Dependency | Version | Purpose |
|---|---|---|
| Go | 1.21.1+ | Runtime environment |
| go-redis/redis | v6.15.9+incompatible | Optional Redis cache backend |
| msgpack/v5 | v5.4.1 | Serialization support |
The library also includes indirect dependencies for testing purposes, including github.com/onsi/ginkgo and github.com/onsi/gomega (go.mod:11-L13).
Install the gofnext package using the standard Go module system:
bash1go get github.com/ahuigo/gofnext
This command downloads the library and adds it to the project's go.mod file. The library follows standard Go module practices and integrates seamlessly with existing Go projects.
After installation, import the package in Go source files:
go1import "github.com/ahuigo/gofnext"
For serialization utilities, import the serial subpackage:
go1import "github.com/ahuigo/gofnext/serial"
Evidence: The import statements are demonstrated across multiple example files including examples/decorator_test.go:9 and examples/serial_test.go:8.
gofnext provides decorator functions to add caching capabilities to existing functions. The library supports functions with 0, 1, 2, or 3 parameters, as well as variants that return errors.
For functions without parameters, use CacheFn0:
go1func getUser() UserInfo { 2 time.Sleep(10 * time.Millisecond) 3 return UserInfo{Name: "Alex", Age: 20} 4} 5 6getUserInfoFromDb := gofnext.CacheFn0(getUser)
Evidence: examples/decorator_test.go:12-L18 demonstrates the zero-parameter caching pattern.
For functions with one parameter, use CacheFn1:
go1getUser := func(age int) UserInfo { 2 time.Sleep(10 * time.Millisecond) 3 return UserInfo{Name: "Alex", Age: age} 4} 5 6getUserInfoCached := gofnext.CacheFn1(getUser)
Evidence: examples/decorator_test.go:26-L33 shows single-parameter function caching.
For functions with two parameters, use CacheFn2 with optional configuration:
go1getUserScore := func(c context.Context, id int) int { 2 fmt.Println("select score from db where id=", id, time.Now()) 3 time.Sleep(10 * time.Millisecond) 4 return 98 + id 5} 6 7getUserScoreWithCache := gofnext.CacheFn2(getUserScore, &gofnext.Config{ 8 TTL: time.Hour, 9})
Evidence: examples/decorator_test.go:44-L54 demonstrates two-parameter caching with TTL configuration.
For functions with three parameters, use CacheFn3:
go1sum := func(a, b, c int) int { 2 time.Sleep(10 * time.Millisecond) 3 return a + b + c 4} 5 6sumCache := gofnext.CacheFn3(sum, &gofnext.Config{ 7 TTL: time.Hour, 8})
Evidence: examples/decorator_test.go:75-L84 shows three-parameter function caching.
The Config struct provides several caching configuration options. The most commonly used option is TTL (Time To Live), which controls cache expiration.
Set the cache expiration time using the TTL field:
go1getUserScoreFromDbWithCache := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ 2 TTL: time.Hour, 3})
Evidence: examples/decorator-key_test.go:27-L29 demonstrates TTL configuration.
For testing or short-lived cache scenarios:
go1getUserScoreFromDbWithCache := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ 2 TTL: time.Millisecond * 10, 3})
Evidence: examples/decorator-ttl_test.go:19-L21 shows a 10-millisecond TTL configuration.
By default, errors are not cached. To cache errors along with successful results, use the ErrTTL configuration:
go1getUserAndErrCached := gofnext.CacheFn1Err(getUserAndErr, &gofnext.Config{ 2 ErrTTL: time.Hour, 3})
Evidence: examples/decorator-err_test.go:61-L63 demonstrates error caching configuration.
gofnext provides separate decorator functions for functions that return errors. Use CacheFn0Err, CacheFn1Err, etc., for functions with error return values.
By default, errors are not cached, causing the function to be re-executed on each call when an error occurs:
go1getUserAndErrCached := gofnext.CacheFn0Err(getUserWithErr, nil)
Evidence: examples/decorator-err_test.go:33 shows the default error handling behavior where errors are not cached.
To cache errors (useful for preventing repeated failed operations), configure ErrTTL:
go1getUserAndErrCached := gofnext.CacheFn1Err(getUserAndErr, &gofnext.Config{ 2 ErrTTL: time.Hour, 3})
Evidence: examples/decorator-err_test.go:51-L63 demonstrates error caching with TTL.
gofnext supports caching for recursive functions, such as Fibonacci calculations:
go1var fib func(int) int 2fib = func(x int) int { 3 if x <= 1 { 4 return x 5 } else { 6 return fib(x-1) + fib(x-2) 7 } 8} 9fib = gofnext.CacheFn1(fib)
Evidence: examples/decorator-fib_test.go:13-L23 demonstrates recursive function caching.
The library supports various key types including structs, maps, slices, and pointers.
go1type UserInfo struct { 2 Name string 3 Age int 4 id int 5} 6 7getUserScore := func(user UserInfo) (int, error) { 8 return 98 + user.id, nil 9} 10 11getUserScoreFromDbWithCache := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ 12 TTL: time.Hour, 13})
Evidence: examples/decorator-key_test.go:12-L29 demonstrates struct key caching.
go1type usermap = map[string]int 2 3getUserScore := func(user usermap) (int, error) { 4 return 98 + user["id"], nil 5} 6 7getUserScoreFromDbWithCache := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ 8 TTL: time.Hour, 9})
Evidence: examples/decorator-key_test.go:72-L86 shows map key caching.
go1getUserScore := func(user *UserInfo) (int, error) { 2 return 98 + user.id, nil 3} 4 5getUserScoreFromDbWithCache := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{ 6 TTL: time.Hour, 7})
Evidence: examples/decorator-key_test.go:170-L188 demonstrates pointer key caching.
For functions with more than 3 parameters, wrap them in a struct:
go1type Stu struct { 2 name string 3 age int 4 gender int 5 height int 6} 7 8getUserScoreOrigin := func(name string, age, gender, height int) int { 9 // implementation 10} 11 12fnWrap := func(arg Stu) int { 13 return getUserScoreOrigin(arg.name, arg.age, arg.gender, arg.height) 14} 15 16fnCachedInner := gofnext.CacheFn1(fnWrap) 17getUserScore := func(name string, age, gender, height int) int { 18 return fnCachedInner(Stu{name, age, gender, height}) 19}
Evidence: examples/decorator_test.go:135-L166 demonstrates the wrapper pattern for functions with more than 3 parameters.
Verify the installation by running the example tests:
bash1go test -v ./examples/...
This command executes all test cases in the examples directory, demonstrating various caching patterns.
Successful test execution should show all tests passing without errors. For example, the Fibonacci test verifies that caching reduces function calls:
go1// TestFib verifies only 7 executions for fib(5) and fib(6) combined 2if excuteCount != 7 { 3 t.Errorf("Expected 7, but got %d", excuteCount) 4}
Evidence: examples/decorator-fib_test.go:27-L29 shows the expected execution count verification.
The library handles concurrent access safely. Tests use parallel execution to verify thread safety:
go1parallelCall(func() { 2 userinfo := getUserInfoCached(20) 3 fmt.Println(userinfo) 4}, 10)
Evidence: examples/decorator_test.go:35-L38 demonstrates parallel execution testing.
Symptom: Function executes multiple times despite caching.
Possible Causes:
Solution: Verify parameter consistency and check TTL configuration. For error cases, configure ErrTTL if error caching is desired:
go1// Default: errors not cached 2getUserAndErrCached := gofnext.CacheFn0Err(getUserWithErr, nil) 3 4// With error caching 5getUserAndErrCached := gofnext.CacheFn1Err(getUserAndErr, &gofnext.Config{ 6 ErrTTL: time.Hour, 7})
Evidence: examples/decorator-err_test.go:29-L47 demonstrates the difference between cached and non-cached error behavior.
Symptom: Cache entries persist longer than configured TTL.
Possible Cause: Insufficient wait time between test calls.
Solution: Ensure adequate sleep time exceeds the TTL:
go1getUserScoreFromDbWithCache(1) 2time.Sleep(time.Millisecond * 11) // wait for ttl timeout (10ms TTL) 3getUserScoreFromDbWithCache(1)
Evidence: examples/decorator-ttl_test.go:24-L28 shows proper TTL timeout testing.
Symptom: Caching behaves unexpectedly with structs containing unexported fields.
Solution: The library handles unexported fields in struct keys. Ensure consistent struct initialization:
go1type UserInfo struct { 2 Name string 3 Age int 4 id int // unexported field 5} 6 7getUserScoreFromDbWithCache(UserInfo{id: 1})
Evidence: examples/decorator-key_test.go:12-L16 demonstrates struct keys with unexported fields.
Symptom: Stack overflow when caching recursive functions.
Solution: Ensure the cache decorator is applied correctly to the recursive function variable:
go1var fib func(int) int 2fib = func(x int) int { 3 if x <= 1 { 4 return x 5 } else { 6 return fib(x-1) + fib(x-2) 7 } 8} 9fib = gofnext.CacheFn1(fib) // Apply after function definition
Evidence: examples/decorator-fib_test.go:13-L23 shows correct recursive function caching.
After completing the quick start, explore the following advanced topics:
serial package for custom serialization needs as shown in examples/serial_test.go:8For detailed API documentation and advanced configuration options, refer to the Usage Guide section.