Search⌘ K
AI Features

Updating Functions to Improve the Markdown Preview Tool

Explore how to improve a Go Markdown preview tool by updating the run function to accept alternative templates and handle errors. Learn to modify main and test functions to incorporate new features, ensuring your application remains flexible and well-tested.

Updating the run() function

Let’s update the definition of the run() function so it accepts another string input parameter called tFname that will represent the name of an alternate template file:

Go (1.6.2)
func run(filename, tFname string, out io.Writer, skipPreview bool) error {

Since the parseContent() function now also returns an error, we update the run() function to handle this condition when calling parseContent(), like this:

Go (1.6.2)
func run(filename, tFname string, out io.Writer, skipPreview bool) error {
// Read all the data from the input file and check for errors
input, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
htmlData, err := parseContent(input, tFname)
if err != nil {
return err
}
// Create temporary file and check for errors
temp, err := ioutil.TempFile("", "mdp*.html")
if err != nil {
return err
}
if err := temp.Close(); err != nil {
return err
}
outName := temp.Name()
fmt.Fprintln(out, outName)
if err := saveHTML(outName, htmlData); err != nil {
return err
}
if skipPreview {
return nil
}
defer os.Remove(outName)
return preview(outName)
}
The run() function
...