How to get root of filesystem in Go in an OS-agnostic way

384 views Asked by At

I want to get the root directory of the filesystem in Go in such a way that it will work on both Windows and Unix.

I thought I could do something like

func fsRootDir() string {
    s := os.Getenv("SystemDrive")
    if s != "" {
        return s
    }
    return "/"
}

However, there are a couple problems with this, so I rejected this approach:

  • A user could create a SystemDrive environment variable on Unix with some bogus path.
  • A user could change the value of the SystemDrive environment variable on Windows to some bogus path.

I looked at this answer to a related question, but this also has some problems:

  • The first option relies on the SystemDrive environment variable, which for the reasons above is not guaranteed to hold the expected value on either Unix or Windows.
  • All other options in this answer rely on os.TempDir. On Windows, os.TempDir uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. I do not believe I can trust that these environment variables have not been modified.

I also considered

func fsRootDir() string {
    if runtime.GOOS == "windows" {
        return "C:"
    }
    return "/"
}

but I thought I read somewhere that it is possible to change the filesystem root on Windows to something other than C:.

How can I get the root directory of a filesystem in such a way that it will work on both Windows and Unix?

1

There are 1 answers

1
dave On

Why not combine the two?

func fsRootDir() string {
    if runtime.GOOS == "windows" {
        return os.Getenv("SystemDrive")
    }
    return "/"
}

A user could change the value of the SystemDrive environment variable on Windows to some bogus path.

No they can't, SystemDrive is a read-only variable.