Cleaning Up Temporary Files

Powerful Command-Line Applications in Go — by Ricardo Gerardi (35 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Adding an Auto-Preview F eature | TOC | Improving the Markdown Pre view Tool with Templates 👉

Currently, our program doesn’t clean up the temporary files because the method we used to create them doesn’t automatically clean them up. As you can see, running the tool multiple times creates different files:

​ ​$ ​​go​​ ​​run​​ ​​main.go​​ ​​-file​​ ​​README.md​
​ /tmp/mdp552496404.html
​ ​$ ​​go​​ ​​run​​ ​​main.go​​ ​​-file​​ ​​README.md​
​ /tmp/mdp016541878.html
​ ​$ ​​ls​​ ​​-ltr​​ ​​/tmp/​​ ​​|​​ ​​grep​​ ​​mdp​
​ -rw------- 1 ricardo users 503 Apr 15 10:25 mdp807323568.html
​ -rw------- 1 ricardo users 503 Apr 15 10:27 mdp552496404.html
​ -rw------- 1 ricardo users 503 Apr 15 10:31 mdp016541878.html

This is expected as the program can’t assume how and when the files will be used. It’s your responsibility to delete the temporary files to keep the system clean. In your program, you can use the function os.Remove to delete the files when they’re no longer needed. In general, you defer the call to this function using the defer statement to ensure the file is deleted when the current function returns.

Update the run function to delete the file like this:

workingFiles/mdp.v4/main.go

​ ​func​ run(filename ​string​, out io.Writer, skipPreview ​bool​) ​error​ {
​ ​// Read all the data…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.