Chapter 3 Working with Files in Go

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Wrapping Up | TOC | Creating a Basic Markdown Prev iew Tool 👉

Working with files is one of the most frequent tasks you have to perform when building your command-line tools. Your programs pull data from files and also save results in them. This is particularly important when working with Linux or Unix because system resources are represented as files.

To get comfortable working with files in CLI apps, you’ll develop a tool to preview Markdown files locally, using a web browser.

Markdown is a lightweight markup language that uses plain text with special syntax to represent formatting compatible with HTML. It’s used to write blog articles, comments, and README files for open source projects like those available in GitHub. Since it uses plain text, writing Markdown requires only a text editor, but it may be hard to visualize the end result.

The tool you’ll write converts the Markdown source into HTML that can be viewed in a browser. To work with files in Go, you’ll use the packages os and io from the standard library. You’ll create and open files so that you can read data or save it to files using different methods. You’ll handle paths consistently across multiple platforms to make your code more flexible, ensuring your tool works in cross-platform scenarios. You’ll use the defer statement to effectively clean up used resources…

--

--

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.