1
0
mirror of https://github.com/securego/gosec.git synced 2025-07-07 00:35:35 +02:00

Rule for defering methods which return errors (#441)

This commit is contained in:
Sam Caccavale
2020-03-01 15:45:37 -05:00
committed by GitHub
parent a2ac0bf32b
commit 7525fe4bb7
6 changed files with 135 additions and 2 deletions

View File

@ -1435,7 +1435,57 @@ func main() {
d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
defer check(err)
fmt.Printf("wrote %d bytes\n", n2)
n3, err := f.WriteString("writes\n")
fmt.Printf("wrote %d bytes\n", n3)
f.Sync()
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4)
w.Flush()
}`}, 1, gosec.NewConfig()}}
// SampleCodeG307 - Unsafe defer of os.Close
SampleCodeG307 = []CodeSample{
{[]string{`package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("/tmp/dat1", d1, 0744)
check(err)
allowed := ioutil.WriteFile("/tmp/dat1", d1, 0600)
check(allowed)
f, err := os.Create("/tmp/dat2")
check(err)
defer f.Close()
d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
defer check(err)
fmt.Printf("wrote %d bytes\n", n2)
n3, err := f.WriteString("writes\n")
@ -1462,6 +1512,7 @@ import (
"log"
"os"
)
func main() {
f, err := os.Open("file.txt")
if err != nil {
@ -1469,6 +1520,13 @@ func main() {
}
defer f.Close()
defer func() {
err := f.Close()
if err != nil {
log.Printf("error closing the file: %s", err)
}
}()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
log.Fatal(err)