golang. reflect makefunc: how to decorate the origin func?

158 Views Asked by At

I'm making a tools that decorte my origin function to test my program. It can inject some specific method to oringin function. Now I'm using reflect to do that:

I will define a Handle function to decorate the origin func. Like inject error to the origin, inject latency to the origin, etc...

When I call decorate to rewrite my origin func, I need a function to set excute "Handle" before the origin or after the origin. So that It can support inject error before call origin or after call origin.

I write my idea to the following code:

package main

import (
    "fmt"
    "reflect"
)



func main() {
    func1 := OriginFunc
    // todo: need a func can set excute new func after origin or befor origin

    Decorate(&func1)

    val, err := func1(1,2)
    ...
}

func OriginFunc(a, b int) (int,error) {
    return a + b, nil
}

func Decorate(a interface{}) {
    v := reflect.ValueOf(a).Elem()
    
    m := reflect.MakeFunc(v.Type(), func(args []reflect.Value) (results []reflect.Value) {
        
        // todo here
        // want to call Handle that support excute it before "OriginFunc" and after "OriginFunc". Just set before or after when I call "Decorate".
        // handle func can be edited by myself
        // example: 
        // if I need excute after OriginFunc to inject error message: excute OriginFunc(1,2) and return 3, err
        // If I need excute before OriginFunc to inject error message: excute new func and just return 0, error
        return Handle()
        
        
    })
    v.Set(m)
    
}

func Handle() {
   // inject error or something...
}
0

There are 0 best solutions below