Skip to content

Instantly share code, notes, and snippets.

@guesslin
Created April 13, 2021 01:03
Show Gist options
  • Save guesslin/31b58e0acef258e137c8aa8c246ebb5a to your computer and use it in GitHub Desktop.
Save guesslin/31b58e0acef258e137c8aa8c246ebb5a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
)
func IncorrectCloseFile(json_data []byte) {
//create json file
json_file, err := os.Create("sample.json")
if err != nil {
fmt.Println(err)
// Not stop the process
}
defer json_file.Close()
json_file.Write(json_data)
// File had already been closed in Line#15, use the defer smart and correct
json_file.Close()
}
// You can choice to not return the error out, but it's good to have the error for the caller
func CloseFile(json_data []byte) error {
//create json file
json_file, err := os.Create("sample.json")
if err != nil {
fmt.Println(err)
return err
}
defer json_file.Close()
json_file.Write(json_data)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment