ruk·si

🐹 Go
Temporary Files

Updated at 2022-01-20 22:28

os contains tools for managing temporary files and directories. These are useful to create files that you mainly need during runtime and can be cleaned up by the operating system between boots.

package main

import (
    "os"
    "path/filepath"
    "strings"
)

func assert(condition bool, details ...interface{}) {
    if !condition {
        for _, detail := range details {
            panic(detail) // will only panic the first detail
        }
        panic("assert failed")
    }
}

func main() {
    f, err := os.CreateTemp("", "sample")
    assert(err == nil, err)

    defer func(name string) {
        err := os.Remove(name)
        assert(err == nil, err)
    }(f.Name())
    assert(strings.HasPrefix(f.Name(), "/tmp/sample")) // and some random number suffix

    _, err = f.Write([]byte{1, 2, 3, 4})
    assert(err == nil, err)

    dir, err := os.MkdirTemp("", "sample-dir")
    assert(err == nil, err)

    defer func(path string) {
        err := os.RemoveAll(path)
        assert(err == nil, err)
    }(dir)
    assert(strings.HasPrefix(dir, "/tmp/sample-dir")) // and some random number suffix

    file := filepath.Join(dir, "file1")
    err = os.WriteFile(file, []byte{1, 2}, 0666)
    assert(err == nil, err)
}