Adding an Auto-Preview Feature
Powerful Command-Line Applications in Go — by Ricardo Gerardi (34 / 127)
👈 Using Interfaces t o Automate Tests | TOC | Cleaning Up Temporary Files 👉
At this moment, your tool isn’t automating the entire process. It converts the Markdown to HTML, but the user still has to open it in a browser to see the results. While this is a valid approach, it would be nice for the user to be able to run the tool and automatically see the results. We’re assuming that most users want this feature, but it’s nice to provide an option to disable it in case they prefer to open the file at a different time. As part of this implementation, we’ll add another flag -s (skip-preview) to skip the auto-preview. This option also helps with executing the tests by avoiding automatically opening the files in the browser for every test.
To preview the file in a browser, let’s add another function to this program called preview. This function takes the temporary file name as input and returns an error in case it can’t open the file. Create this function by adding this code at the end of your main.go file:
func preview(fname string) error {
cName := ""
cParams := []string{}
// Define executable based on OS
switch runtime.GOOS {
case "linux":
cName = "xdg-open"
case "windows":
cName = "cmd.exe"
cParams = []string{"/C", "start"}
…