If you need to check if a file exists using Go, then you can use one of the following methods, depending on the version of Go you may be using.

If you are using Go >=1.13, then

1
2
3
4
file, err := os.OpenFile("/path/to/file.txt")
if errors.Is(err, os.ErrNotExist) {
    // The file does not exists
}

However, it is also possible to trap an error from an OpenFile attempt:

1
2
3
4
file, err := os.OpenFile("/path/to/file.txt")
if os.IsNotExist(err) {
    // The file does not exists
}

You can also confirm if the path is also not a directory as follows:

1
2
3
4
5
6
7
func fileExists(filename string) bool {
    info, err := os.Stat(filename)
    if os.IsNotExist(err) {
        return false
    }
    return !info.IsDir()
}