.Close
method GO-S230747 if err != nil {
48 return err
49 }
50 defer resp.Body.Close()51
52 // Create the file
53 out, err := os.Create(filepath)
54 if err != nil {
55 return err
56 }
57 defer out.Close()58
59 // Write the body to file
60 _, err = io.Copy(out, resp.Body)
54 if err != nil {
55 return err
56 }
57 defer out.Close()58
59 // Write the body to file
60 _, err = io.Copy(out, resp.Body)
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.
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")
}
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()
}