github.com/lyraproj/hiera@v1.0.0-rc4/session/serverctx_test.go (about) 1 package session_test 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/lyraproj/dgo/dgo" 8 "github.com/lyraproj/dgo/vf" 9 "github.com/lyraproj/hiera/api" 10 "github.com/lyraproj/hiera/hiera" 11 sdk "github.com/lyraproj/hierasdk/hiera" 12 ) 13 14 func ExampleServerContext_CachedValue() { 15 cachingProvider := func(pc sdk.ProviderContext, key string) dgo.Value { 16 ic := pc.(api.ServerContext) 17 if v, ok := ic.CachedValue(key); ok { 18 fmt.Printf("Returning cached value for %s\n", key) 19 return v 20 } 21 fmt.Printf("Creating and caching value for %s\n", key) 22 v := ic.Interpolate(vf.String(fmt.Sprintf("value for %%{%s}", key))) 23 ic.Cache(key, v) 24 return v 25 } 26 27 hiera.DoWithParent(context.Background(), cachingProvider, nil, func(hs api.Session) { 28 s := map[string]interface{}{ 29 `a`: `scope 'a'`, 30 `b`: `scope 'b'`, 31 } 32 ic := hs.Invocation(s, nil) 33 fmt.Println(hiera.Lookup(ic, `a`, nil, nil)) 34 fmt.Println(hiera.Lookup(ic, `b`, nil, nil)) 35 fmt.Println(hiera.Lookup(ic, `a`, nil, nil)) 36 fmt.Println(hiera.Lookup(ic, `b`, nil, nil)) 37 }) 38 // Output: 39 // Creating and caching value for a 40 // value for scope 'a' 41 // Creating and caching value for b 42 // value for scope 'b' 43 // Returning cached value for a 44 // value for scope 'a' 45 // Returning cached value for b 46 // value for scope 'b' 47 }