go / expert
Snippet
Dynamic Interface Proxy Generation Using reflect.MakeFunc for Test Mocks
Go's reflect.MakeFunc dynamically creates a function of a given signature at runtime. This allows building generalized proxy adapters, interception wrappers, and mocking hooks for unit testing without manually writing boilerplate interface methods.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package mainimport ("fmt""reflect")type Calculator func(int, int) intfunc CreateLoggingProxy(fn Calculator) Calculator {fnVal := reflect.ValueOf(fn)fnType := fnVal.Type()proxy := reflect.MakeFunc(fnType, func(args []reflect.Value) []reflect.Value {a := args[0].Int()b := args[1].Int()fmt.Printf("[LOG] Intercepted call with args: %d, %d\n", a, b)out := fnVal.Call(args)fmt.Printf("[LOG] Return value: %d\n", out[0].Int())return out})return proxy.Interface().(Calculator)}func main() {add := func(a, b int) int { return a + b }proxyAdd := CreateLoggingProxy(add)res := proxyAdd(5, 7)fmt.Println("Result:", res)}
Breakdown
1
proxy := reflect.MakeFunc(fnType, func(args []reflect.Value) []reflect.Value {
Constructs a new callable reflect.Value of type fnType wrapping a closure that intercepts input arguments and output values.