github.com/ChicK00o/awgo@v0.29.4/cache_examples_test.go (about)

     1  // Copyright (c) 2018 Dean Jackson <deanishe@deanishe.net>
     2  // MIT Licence - http://opensource.org/licenses/MIT
     3  
     4  package aw
     5  
     6  import (
     7  	"fmt"
     8  	"io/ioutil"
     9  	"os"
    10  	"time"
    11  )
    12  
    13  func ExampleCache() {
    14  	var (
    15  		// Cache "key" (filename) and the value to store
    16  		name  = "LastOpened"
    17  		value = time.Now()
    18  	)
    19  
    20  	// Create a temporary directory for Cache to use
    21  	dir, err := ioutil.TempDir("", "awgo-demo")
    22  	if err != nil {
    23  		panic(err)
    24  	}
    25  	defer os.RemoveAll(dir)
    26  
    27  	// Create a new cache
    28  	c := NewCache(dir)
    29  
    30  	// Cache doesn't exist yet
    31  	fmt.Println(c.Exists(name)) // -> false
    32  
    33  	// The API uses bytes
    34  	data, _ := value.MarshalText()
    35  
    36  	if err := c.Store(name, data); err != nil {
    37  		panic(err)
    38  	}
    39  
    40  	// Cache now exists
    41  	fmt.Println(c.Exists(name)) // -> true
    42  
    43  	// Load data from cache
    44  	data, err = c.Load(name)
    45  	if err != nil {
    46  		panic(err)
    47  	}
    48  
    49  	v2 := time.Time{}
    50  	_ = v2.UnmarshalText(data)
    51  
    52  	// Values are equal
    53  	fmt.Println(value.Equal(v2)) // -> true
    54  
    55  	// Output:
    56  	// false
    57  	// true
    58  	// true
    59  }
    60  
    61  // LoadOrStore loads data from cache if they're fresh enough, otherwise it calls
    62  // the reload function for new data (which it caches).
    63  func ExampleCache_LoadOrStore() {
    64  	var (
    65  		name        = "Expiring"
    66  		data        = []byte("test")
    67  		maxAge      = time.Millisecond * 1000
    68  		start       = time.Now()
    69  		reloadCount int
    70  	)
    71  
    72  	// Create a temporary directory for Cache to use
    73  	dir, err := ioutil.TempDir("", "awgo-demo")
    74  	if err != nil {
    75  		panic(err)
    76  	}
    77  	defer os.RemoveAll(dir)
    78  
    79  	// Create a new cache
    80  	c := NewCache(dir)
    81  
    82  	// Called by LoadOrStore when cache is empty or has expired
    83  	reload := func() ([]byte, error) {
    84  		// Log call count
    85  		reloadCount++
    86  		fmt.Printf("reload #%d\n", reloadCount)
    87  
    88  		return data, nil
    89  	}
    90  
    91  	// Cache is empty
    92  	fmt.Println(c.Exists(name)) // -> false
    93  
    94  	out, err := c.LoadOrStore(name, maxAge, reload)
    95  	if err != nil {
    96  		panic(err)
    97  	}
    98  
    99  	// Reload was called and cache exists
   100  	fmt.Println(c.Exists(name)) // -> true
   101  
   102  	// Value is the same
   103  	fmt.Println(string(out) == string(data)) // -> true
   104  
   105  	// Load again, this time from cache, not reload
   106  	out, err = c.LoadOrStore(name, maxAge, reload)
   107  	if err != nil {
   108  		panic(err)
   109  	}
   110  
   111  	// Value is the same
   112  	fmt.Println(string(out) == string(data)) // -> true
   113  
   114  	// Wait for cache to expire, then try again
   115  	time.Sleep(time.Millisecond + maxAge - time.Since(start))
   116  
   117  	// reload is called again
   118  	out, err = c.LoadOrStore(name, maxAge, reload)
   119  	if err != nil {
   120  		panic(err)
   121  	}
   122  
   123  	// Value is the same
   124  	fmt.Println(string(out) == string(data)) // -> true
   125  
   126  	// Output:
   127  	// false
   128  	// reload #1
   129  	// true
   130  	// true
   131  	// true
   132  	// reload #2
   133  	// true
   134  }
   135  
   136  // LoadOrStoreJSON marshals JSON to/from the cache.
   137  func ExampleCache_LoadOrStoreJSON() {
   138  	var (
   139  		name   = "Host"
   140  		maxAge = time.Second * 5
   141  	)
   142  
   143  	// Create a temporary directory for Cache to use
   144  	dir, err := ioutil.TempDir("", "awgo-demo")
   145  	if err != nil {
   146  		panic(err)
   147  	}
   148  	defer os.RemoveAll(dir)
   149  
   150  	// struct to cache
   151  	type host struct {
   152  		Hostname string
   153  		Port     int
   154  	}
   155  
   156  	// Called by LoadOrStoreJSON. Returns default host.
   157  	// Normally, this function would do something that takes some time, like
   158  	// fetch data from the web or an application.
   159  	reload := func() (interface{}, error) {
   160  		fmt.Println("reload")
   161  
   162  		return &host{
   163  			Hostname: "localhost",
   164  			Port:     6000,
   165  		}, nil
   166  	}
   167  
   168  	// Create a new cache
   169  	c := NewCache(dir)
   170  
   171  	// Cache is empty
   172  	fmt.Println(c.Exists(name)) // -> false
   173  
   174  	// Populate new host from cache/reload
   175  	h := &host{}
   176  	if err := c.LoadOrStoreJSON(name, maxAge, reload, h); err != nil {
   177  		panic(err)
   178  	}
   179  
   180  	fmt.Println(h.Hostname)
   181  	fmt.Println(h.Port)
   182  
   183  	// Output:
   184  	// false
   185  	// reload
   186  	// localhost
   187  	// 6000
   188  }