Question
Should I use log.Fatalf in my main function?
I'm using Golang to write a script that produces a file. At the moment, I'm testing the process with the following code:
func main() {
var builder strings.Builder
keys := []int{1, 2, 3, 4}
for _, key := range keys {
// Add Iso3166 templates
builder.WriteString(fmt.Sprintf("This is key %v", key)
builder.WriteString("\n\n")
}
file, err := os.Create(fileName)
if err != nil {
log.Fatalf("Failed to create file: %v", err)
}
defer file.Close()
_, err = file.Write([]byte(standardBeginning))
if err != nil {
log.Fatalf("Failed to write iso3166: %v", err)
}
}
This code works, but I get the following warning in the IDE:
log.Fatalf will exit, and `defer file.Close()` will not run
I've read around to see what I should do about this, particularly this question here: Should a Go package ever use log.Fatal and when?. But I'm still not sure if log.Fatalf is reasonable to use in my situation.
Am I in danger of leaving my file open? Is there a better way to handle errors like this?