I want to try open a PE file with a timeout in Go. To achieve this, I am using anonymous function while channeling out the file pointer and error. I use the select clause with a timeout case to enforce the timeout as shown below.
go func() {
f, e := pe.Open(filePath)
file <- f
err <- e
}()
select {
case <-fileOpenTimeout:
fmt.Printf("ERROR: Opening PE file timed out")
return
case fileError := <-err:
if fileError == nil{...}
}
This code works fine for my use case. However, this may lead to resource leakage if the file takes too long to open. How can I prevent this? Is there a better way to enforce timeout on opening the PE file?