more reflection for nicer cache filling types

This commit is contained in:
Ted Unangst 2019-10-04 14:08:40 -04:00
parent 191406b486
commit f0dfb6c082
2 changed files with 15 additions and 4 deletions

View File

@ -28,10 +28,22 @@ type Cache struct {
lock sync.Mutex
}
func cacheNew(filler cacheFiller) *Cache {
func cacheNew(fillfn interface{}) *Cache {
c := new(Cache)
c.cache = make(map[interface{}]interface{})
c.filler = filler
ftype := reflect.TypeOf(fillfn)
if ftype.Kind() != reflect.Func {
panic("cache filler is not function")
}
if ftype.NumIn() != 1 || ftype.NumOut() != 2 {
panic("cache filler has wrong argument count")
}
c.filler = func(key interface{}) (interface{}, bool) {
vfn := reflect.ValueOf(fillfn)
args := []reflect.Value{reflect.ValueOf(key)}
rv := vfn.Call(args)
return rv[0].Interface(), rv[1].Bool()
}
return c
}

3
web.go
View File

@ -1141,8 +1141,7 @@ func showhonkers(w http.ResponseWriter, r *http.Request) {
}
}
var combocache = cacheNew(func(key interface{}) (interface{}, bool) {
userid := key.(int64)
var combocache = cacheNew(func(userid int64) ([]string, bool) {
honkers := gethonkers(userid)
var combos []string
for _, h := range honkers {