Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsafe defer of os.Close #42

Closed
uzaxirr opened this issue Jan 3, 2023 · 1 comment
Closed

Unsafe defer of os.Close #42

uzaxirr opened this issue Jan 3, 2023 · 1 comment
Labels
bug Something isn't working good first issue Good for newcomers

Comments

@uzaxirr
Copy link
Member

uzaxirr commented Jan 3, 2023

Description

Calling os.Close on an io.Closer may return an error, and ignoring the same might result in a data loss.

Occurrences

There are 3 occurrences of this issue in the repository.

See all occurrences on DeepSource → deepsource.io/gh/ZeStream/zestream-server/issue/GO-S2307/occurrences/
Screenshot 2023-01-03 at 10 49 10 AM

Suggestions

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")
}

Recommend

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()
}
@uzaxirr uzaxirr added bug Something isn't working good first issue Good for newcomers labels Jan 3, 2023
@akshay1027
Copy link

I am working on this @uzaxirr @abhishekraj272. I have recently started learning Go and using this repo to learn simultaneously!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

3 participants