0

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...
}
Pkzzz
  • 101
  • 1
  • 7
  • 3
    You can't decorate nor modify a function. Not with reflection. You can use reflection to change a function **value**, but that's not the same as changing a function. `func Handle() { ... }` will always be `func Handle() { ... }`, you can't modify it at runtime. – mkopriva Oct 28 '22 at 10:35
  • 3
    "I'm making a tools that decorte my origin function to test my program." That's very pythonic. If you want to learn Go, don't apply interpreted-style thinking to the language. You should avoid reflect altogether until you have a solid grasp of the language. – erik258 Oct 28 '22 at 12:02
  • Got it, but is there any way to control the excute order? Like excute decorate and return the changed value, or return as the first step? – Pkzzz Oct 31 '22 at 09:25

0 Answers0