github.com/clysto/awgo@v0.15.0/cache_examples_test.go (about)

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