Skip to content

Instantly share code, notes, and snippets.

@mapix
Created May 6, 2018 11:33
Show Gist options
  • Save mapix/0d9eb19f16b39d2050edef2324388b3d to your computer and use it in GitHub Desktop.
Save mapix/0d9eb19f16b39d2050edef2324388b3d to your computer and use it in GitHub Desktop.

Revisions

  1. mapix created this gist May 6, 2018.
    37 changes: 37 additions & 0 deletions deco.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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!")
    }