Senior
// Need to modify the wrapper function to work with a specified timeout (for example, 1 second). // If the "long" function completes within this time - great, return the result. // If not - return an error. The result of the operation in this case does not matter. // // Additionally, measure how long this function took to execute (just log it). // The signature of the wrapper function can be changed.
sobes.tech AI
Answer from AI
Below is an example of a wrapper function in Go that runs a given function with a 1-second timeout, measures execution time, and returns an error if the time is exceeded:
package main
import (
"errors"
"log"
"time"
)
// TimeoutWrapper runs the function fn with a timeout
func TimeoutWrapper(fn func() (interface{}, error), timeout time.Duration) (interface{}, error) {
start := time.Now()
resultChan := make(chan interface{})
errChan := make(chan error)
go func() {
res, err := fn()
if err != nil {
errChan <- err
return
}
resultChan <- res
}()
select {
case res := <-resultChan:
elapsed := time.Since(start)
log.Printf("Function completed in %v", elapsed)
return res, nil
case err := <-errChan:
elapsed := time.Since(start)
log.Printf("Function errored in %v", elapsed)
return nil, err
case <-time.After(timeout):
elapsed := time.Since(start)
log.Printf("Function timed out after %v", elapsed)
return nil, errors.New("function timed out")
}
}
// Example of a "long" function
func longFunc() (interface{}, error) {
time.Sleep(2 * time.Second) // simulate long work
return "done", nil
}
func main() {
res, err := TimeoutWrapper(longFunc, 1*time.Second)
if err != nil {
log.Println("Error:", err)
} else {
log.Println("Result:", res)
}
}
In this example, the TimeoutWrapper function runs the passed function in a goroutine, waits for its result or error, or a timeout. The execution time is logged in any case.