How to create temporary files in go
Software Engineer with an entrepreneurship gene. Love talking about code, products, UI/UX and how to build startups.
Search for a command to run...
Software Engineer with an entrepreneurship gene. Love talking about code, products, UI/UX and how to build startups.
No comments yet. Be the first to comment.
Goroutines are one of the best features of Go language. It is very easy to run a function as a goroutine, you just have to use the keyword go before the function call. Here is a very simple function which sleeps for n seconds and prints a line. pa...

In a previous post, we saw how we can use Regular expressions in Go to match and replace patterns in a string. While regexps are very useful, you might not want to them for every time you want to do some basic string manipulation. The strings package...

Go is a modern language, but doesn't use try-except blocks to handle errors. Errors are simple values that can be returned from functions and it is common to check for errors before proceeding with your next steps. Let's see the different ways to cre...

In the previous post, we saw how to write a simple unit test case and also how to write table driven test cases. In this post we will quickly see how to write benchmarks, as go supports running benchmarks on your functions as part of the standard tes...
Go has built-in support for writing test cases for your code. And it is important to write as much test cases as possible to make sure you cover all possible conditions. You have to use the testing standard package to write your unit test cases. Let...
Pro Golang Dev
14 posts
When programming in python, one of the common modules I used often is the tempfile module. This module contains functions which create temporary files and returns a file object. This is useful if you are downloading large files and want to cleanup automatically once you are done.
Go has similar functions. Lets look at a sample code which create temporary folders and files and writes to it.
Here is the example source code of the program.
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
// Create a Temp File: This will create a filename like /tmp/pre-23423234
// If we use a pattern like "pre-*.ext", you can get a file like: /tmp/pre-23423234.ext
tmpFile, err := ioutil.TempFile(os.TempDir(), "pre-")
if err != nil {
fmt.Println("Cannot create temporary file", err)
}
// cleaning up by removing the file
defer os.Remove(tmpFile.Name())
fmt.Println("Created a Temp File: " + tmpFile.Name())
// Write to the file
text := []byte("Writing some text into the temp file.")
if _, err = tmpFile.Write(text); err != nil {
fmt.Println("Failed to write to temporary file", err)
}
// Close the file
if err := tmpFile.Close(); err != nil {
fmt.Println(err)
}
}
The io/ioutil package contains two function TempDir and TempFile to create a temporary directory and a temporary file.
By default on a unix machine, the TempDir function returns /tmp/ as the temporary directory. You can pass in additional parameters to create directories with prefixes.
The TempFile function creates a unique and random number. You can control the prefix and suffix of the file with the pattern parameter. By passing example-*.tmp, you will create temporary files. This is useful if you don't want to delete the temporary files in the program, but instead want to have a batch delete job which cleans up the temporary files later.
Once the file is created, you can write anything into the file as it is of type os.File. And since os.File implements the io.ReadWriter interface, you can write into the file using the Write method.