ZeStream / zestream-server

an open-sourced alternative to cloudinary [video streaming done ✅, image/audio under dev 🔨 ]
GNU General Public License v3.0
203 stars 41 forks source link

Unsafe defer of `os.Close` #42

Closed uzaxirr closed 1 year ago

uzaxirr commented 1 year ago

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()
}
akshay1027 commented 1 year ago

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