Skip to content

Golang Unsafe Defer Call

What does this mean ?

Deferring a method which returns an error.

What can happen ?

This will lead to incorrect behaviour during the run-time of the application, and it may lead to crashing the application.

Recommendation

It’s an idiom that quickly becomes rote to Go programmers:whenever you conjure up a value that implements the io.Closer interface, after checking for errors you immediately defer its Close() method. You see this most often when making HTTP requests.But this idiom is actually harmful for writable files because deferring a function call ignores its return value, and the Close() method can return errors. For writable files, Go programmers should avoid the defer idiom or very infrequent, maddening bugs will occur.

Sample Code

Vulnerable :

f, err := os.Open("/home/note/notes.txt")
if err != nil {
    return err
}
defer f.Close()

Non Vulnerable :

func helloNotes() error {
    f, err := os.Create("/home/note/notes.txt")
    if err != nil {
        return err
    }
    defer f.Close()

    if err = io.WriteString(f, "hello note"); err != nil {
        return err
    }

    return f.Sync()
}

References