Skip to content

Instantly share code, notes, and snippets.

@jonbodner
Created December 28, 2017 20:14
Show Gist options
  • Save jonbodner/afb7d30e0b7aaa579b88542f5bdb887b to your computer and use it in GitHub Desktop.
Save jonbodner/afb7d30e0b7aaa579b88542f5bdb887b to your computer and use it in GitHub Desktop.
func buildInStruct(ft reflect.Type) (reflect.Type, error) {
if ft.NumIn() == 0 {
return nil, errors.New("Must have at least one param")
}
var sf []reflect.StructField
for i := 0; i < ft.NumIn(); i++ {
ct := ft.In(i)
if !ct.Comparable() {
return nil, fmt.Errorf("parameter %d of type %s and kind %v is not comparable", i+1, ct.Name(), ct.Kind())
}
sf = append(sf, reflect.StructField{
Name: fmt.Sprintf("F%d", i),
Type: ct,
})
}
s := reflect.StructOf(sf)
return s, nil
}
func Cacher(f interface{}, expiration time.Duration) (interface{}, error) {
ft := reflect.TypeOf(f)
if ft.Kind() != reflect.Func {
return nil, errors.New("Only for functions")
}
inType, err := buildInStruct(ft)
if err != nil {
return nil, err
}
if ft.NumOut() == 0 {
return nil, errors.New("Must have at least one returned value")
}
fmt.Println("inType looks like", inType)
return f, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment