Create Test Files in Your Temp Directory

When running tests that require static files/directories to be generated, I used to just create them in the same working directory wherever the go test command was executed. It was either that, or hardcoding a path.

Now, I use the os.TempDir() function so that file/directory generating tests would be less invasive to an environment.

As the docs mention about os.TempDir():

TempDir returns the default directory to use for temporary files.  

The source is also surprisingly simple:

func TempDir() string {  
    dir := Getenv("TMPDIR")
      if dir == "" {
        if runtime.GOOS == "android" {
          dir = "/data/local/tmp"
        } else {
          dir = "/tmp"
    return dir


This may not be a surprise to many, but I haven't ever really googled this specific question or come across this detail in an article. Finding a function such as TempDir() was intuitive after observing more of the common functions in the os package.

Don't forget to use the path/filepath function Join() when manipulating paths. It is OS agnostic, so there's no need to create OS specific append functions.

A few other useful functions of the os package include os.Chdir(), os.Chmod(), and os.MkDir. Do take a look at the package summary, there's bound to be something else that's really useful. Cheers!