Get file size

https://codeeval.dev/gist/ef21b4629b5650feda628b673e0cb5e5

Instead of os.Stat we can also use os.Lstat. The difference is that os.Stat follows symbolic links and os.Lstat doesn’t.

In other words: for a symbolic link os.Lstat returns information about link and os.Stat about the file that it links to.

Get information about the file

https://codeeval.dev/gist/f3200e74ea0cb6cb456b2c973c7bd9ce

Check if a file exists

https://codeeval.dev/gist/076b9dc06c9fa4db02a52c8c3ec828e8

Checking if a file exists is surprisingly tricky and it’s impossible to write a generic function that handles all the nuances.

Here are decisions we made:

Delete a file

path := "foo.txt"
err := os.Remove(path)
if err != nil {
    if os.IsNotExist(err) {
        fmt.Printf("os.Remove failed because file doesn't exist\\n")
    } else {
        fmt.Printf("os.Remove failed with '%s'\\n", err)
    }
}

os.Remove returns an error for files that don’t exist.

Usually you want to ignore such errors which you can do by testing error with os.IsNotExist(err).

Rename a file

oldPath := "old_name.txt"
newPath := "new_name.txt"
err := os.Rename(oldPath, newPath)
if err != nil {
    fmt.Printf("os.Rename failed with '%s'\\n", err)
}

Copy a file