ruk·si

🐹 Go
Context Managers

Updated at 2013-11-22 07:44

Error handling and resource management must be done but this causes a lot of boilerplate code.

func OpenAndReadFile(name string) {
    fi, err := os.Open(name)
    if err != nil{
        panic(err)
    }

    b, err := ioutil.ReadAll(fi)
    if err != nil{
        panic(err)
    }

    // Do something with the data.
    fmt.Println(string(b))

    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()
}
// Usage:
OpenAndReadFile("input.txt");

Context managers allows you to reduce that boilerplate code and improves reusability.

func OpenFile(name string, cb func(f io.ReadWriteCloser)) {
    fi, err := os.Open(name)
    if err != nil{
        panic(err)
    }
    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()
    cb(fi)
}
// Usage:
OpenFile("input.txt", func(f io.ReadWriteCloser){
    b, err := ioutil.ReadAll(f)
    if err != nil {
        panic(err)
    }

    // Do something with the data.
    fmt.Println(string(b))
})

Sources