We've created and made use of files for a number of examples so far. We've also had to manually deal with cleanup, name collision, and more. Temporary files and directories are a quicker, simpler way to handle these cases.
Working with temporary files
Getting ready
Refer to the Getting ready section's steps in the Using the common I/O interfaces recipe.
How to do it...
These steps cover writing and running your application:
- From your terminal/console application, create a new directory called chapter1/tempfiles.
- Navigate to this directory.
- Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter1/tempfiles, or use this as an exercise to write some of your own code!
- Create a file called temp_files.go with the following contents:
package tempfiles
import (
"fmt"
"io/ioutil"
"os"
)
// WorkWithTemp will give some basic patterns for working
// with temporary files and directories
func WorkWithTemp() error {
// If you need a temporary place to store files with
// the same name ie. template1-10.html a temp directory
// is a good way to approach it, the first argument
// being blank means it will use create the directory
// in the location returned by
// os.TempDir()
t, err := ioutil.TempDir("", "tmp")
if err != nil {
return err
}
// This will delete everything inside the temp file
// when this function exits if you want to do this
// later, be sure to return the directory name to the
// calling function
defer os.RemoveAll(t)
// the directory must exist to create the tempfile
// created. t is an *os.File object.
tf, err := ioutil.TempFile(t, "tmp")
if err != nil {
return err
}
fmt.Println(tf.Name())
// normally we'd delete the temporary file here, but
// because we're placing it in a temp directory, it
// gets cleaned up by the earlier defer
return nil
}
- Create a new directory named example.
- Navigate to example.
- Create a main.go file with the following contents and ensure that you modify the tempfiles imported to use the path you set up in step 2:
package main
import "github.com/agtorre/go-cookbook/chapter1/tempfiles"
func main() {
if err := tempfiles.WorkWithTemp(); err != nil {
panic(err)
}
}
- Run go run main.go.
- You may also run these:
go build
./example
You should see (with a different path) the following output:
$ go run main.go
/var/folders/kd/ygq5l_0d1xq1lzk_c7htft900000gn/T
/tmp764135258/tmp588787953
- If you copied or wrote your own tests, go up one directory and run go test, and ensure all tests pass.
How it works...
Creating temporary files and directories can be done using the ioutil package. Although you must still delete the files yourself, RemoveAll is the convention, and it will do that for you with only one extra line of code.
When writing tests, the use of temporary files is highly recommended. It's also useful for things such as build artifacts and more. The Go ioutil package will try and honor the OS preferences by default, but it allows you to fall back to other directories if required.