Package os

https://golang.org/pkg/os/

Table of Contents

Open and close a file correctly howto

import "os"

// Simple
func foo(path string) {
    f, err := os.Open(path)

    if err != nil {
        panic(err)
    }

    defer f.Close()
}

// Robust
func bar(path string) (err error) {
    f, err := os.Open(path)

    if err != nil {
        return
    }

    defer func() {
        cerr := f.Close()
        if err == nil {
            err = cerr
        }
    }()

    err = DoSomething(f)
    return
}