~evanj/cms

ref: afc228cb59683180b3b2957aceb6bf1aa0bf0d0e cms/internal/s/cache/cache_generic.go2 -rw-r--r-- 617 bytes
afc228cbEvan J Feat(db): Tweaking db.SetMaxOpenConns, db.SetMaxIdleConns, and 1 year, 25 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package cache

import (
	"encoding/json"
	"github.com/bradfitz/gomemcache/memcache"
)

func StoreAndLoad[type T](mc *memcache.Client, breakCache bool, key string, val T, getter func() (T, error)) (it T, err error) { 
  cached, err := mc.Get(key)
  if err != nil || breakCache { 
    it, err = getter()
    if err != nil { 
      return it, err
    }

		bytes, err := json.Marshal(it)
		if err != nil {
      return it, err
		}

    if err := mc.Set(&memcache.Item{Key: key, Value: bytes}); err != nil { 
      return it, err
    }

    return it, nil
  }

	err = json.Unmarshal(cached.Value, &it)
  return it, err
}