Adding Temporary Files to the Markdown Preview Tool

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Writing Tests for the Markdo wn Preview Tool | TOC | Using Interfaces t o Automate Tests 👉

In its current version, the mdp tool creates an HTML file with the same name as the Markdown file in the current directory. This isn’t ideal as these files can accumulate on your system or could cause a clash if two or more users are previewing the same file simultaneously.

To address this issue, let’s make a change to the mdp tool to create and use temporary files instead of local files. The ioutil package provides a function TempFile to create temporary files with a random name. This allows it to run safely concurrently because the file names will never clash.

The ioutil.TempFile function takes two arguments. The first is the directory where you create the file. If left blank, it uses the system-defined temporary directory. The second argument is a pattern that helps generate file names that are easier to find if desired. To add this functionality to your tool, let’s change the run function.

First, delete the package path/filepath from your import section since you’re no longer using the function filepath.Base to extract the current file name.

​ ​"path/filepath"​

Then, use the function ioutil.TempFile to create the temporary file using the pattern mdp*.html…

--

--

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.