Home  >  Article  >  Backend Development  >  How Can I Create a Function Wrapper in Go to Inject Code Before and After Function Execution?

How Can I Create a Function Wrapper in Go to Inject Code Before and After Function Execution?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 05:31:14501browse

How Can I Create a Function Wrapper in Go to Inject Code Before and After Function Execution?

Function Wrapper in Go

Problem Statement:
You seek a function wrapper that accepts a function and returns its modified version. This wrapper aims to inject custom code execution both before and after the original function call.

Solution:
In Go, you can achieve this by leveraging function literals. Given a specific function signature, a wrapper function can be created to receive and return functions with the same signature. The wrapper function incorporates the desired custom behavior.

Let's consider an example:

func myfunc(i int) int {
    fmt.Println("myfunc called with", i)
    return i * 2
}

Modifying and Enhancing the Function:
The following wrapper function adds logging statements before and after calling the original myfunc:

func wrap(f func(i int) int) func(i int) int {
    return func(i int) (ret int) {
        fmt.Println("Before, i =", i)
        ret = f(i) // Invokes the provided function
        fmt.Println("After, ret =", ret)
        return
    }
}

Usage and Demonstration:
To illustrate, the wrapped function is assigned to a variable and executed:

wf := wrap(myfunc)
ret := wf(2)
fmt.Println("Returned:", ret)

Output:

Before, i = 2
myfunc called with 2
After, ret = 4
Returned: 4

Extending to Multiple Function Types:
This concept can be extended to support wrapping functions with varying parameter and return types by creating separate wrapper functions for each distinct type. For instance, wrapping functions with no parameters or return types:

func wrap(f func()) func() {
    return func() {
        fmt.Println("Before func()")
        f()
        fmt.Println("After func()")
    }
}

func wrapInt2Int(f func(i int) int) func(i int) int {
    return func(i int) (ret int) {
        fmt.Println("Before func(i int) (ret int), i =", i)
        ret = f(i)
        fmt.Println("After func(i int) (ret int), ret =", ret)
        return
    }
}

The above is the detailed content of How Can I Create a Function Wrapper in Go to Inject Code Before and After Function Execution?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn