Created
May 6, 2018 11:33
-
-
Save mapix/0d9eb19f16b39d2050edef2324388b3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"runtime" | |
) | |
func Decorator(decoPtr, fn interface{}) (err error) { | |
var decoratedFunc, targetFunc reflect.Value | |
decoratedFunc = reflect.ValueOf(decoPtr).Elem() | |
targetFunc = reflect.ValueOf(fn) | |
var funcName = runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() | |
v := reflect.MakeFunc(targetFunc.Type(), | |
func(in []reflect.Value) (out []reflect.Value) { | |
// fmt.Println("before") | |
out = targetFunc.Call(in) | |
fmt.Println("funcName", funcName) | |
fmt.Println("args", in) | |
// fmt.Println("after") | |
return | |
}) | |
decoratedFunc.Set(v) | |
return | |
} | |
func bar(a, b string) string { | |
return a + b | |
} | |
func main() { | |
mybar := bar | |
Decorator(&mybar, bar) | |
mybar("hello,", "world!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment