Go

Go

Made by DeepSource

Unsafe defer of .Close method GO-S2307

Security
Major
cwe-703

Calling Close() method may return an error, and ignoring the same might result in a data loss. This is similar to many more Close methods.

For example, on POSIX systems, os.Close uses the close system call underneath, which may return an EIO:

A previously-uncommitted write(2) encountered an input/output error.

This means that the data written by os.Write hasn't been written to the disk, which results in a data loss. It is recommended to handle the error returned by the os.Close call or call os.Sync if available to force the OS to write the data to the disk.

Bad practice

package main

import (
    "fmt"
    "os"
)

func foo() error {
    f, err := os.Create("/tmp/test.txt")
    if err != nil {
        return err
    }
    defer f.Close()

    return fmt.Fprint(f, "Hello World")
}

Recommended

package main

import (
    "fmt"
    "os"
)

func foo() error {
    f, err := os.Create("/tmp/test.txt")
    if err != nil {
        return err
    }

    err = fmt.Fprint(f, "Hello World")
    if err != nil {
        return err
    }

    return f.Close()
}
package main

import (
    "fmt"
    "os"
)

func foo() error {
    f, err := os.Create("/tmp/test.txt")
    if err != nil {
        return err
    }
    defer f.Close()

    err = fmt.Fprint(f, "Hello World")
    if err != nil {
        return err
    }

    return f.Sync()
}

References