A non-keyed cache using the SWR (stale-while-revalidate) pattern.
package main
import (
"time"
"github.com/angablue/swr"
)
func main() {
c, err := swr.New(func() (string, error) {
return "hello", nil
}, time.Second*30)
}- The initial fetch is blocking and triggered by the first call to
Get(). - All other calls to
Get()before the initial fetch returns will also block until the initial fetch returns. - If the initial fetch errors, all calls to
Get()prior to the return will also error. - The following call to
Get()will behave as if it was the first call, performing a blocking fetch.
- Once a fetch has succeeded, the value will be cached and subsequent calls to
Get()will always return the cached value. - Once the value becomes stale, the cache will keep returning the stale value while fetching a new value in the background.
- If the background refresh errors, the cache will not be updated and the following call to
Get()will trigger another background refresh. - If the background refresh succeeds, the value is cached and all subsequent calls to
Get()will yield the fresh value.