Reading and Writing to Files
Explore reading and writing files in Go for DevOps tasks. Understand how to work with local files using os.ReadFile and os.WriteFile, convert data types, and stream remote files efficiently. Gain foundational skills to manipulate configuration and data files in various formats.
We'll cover the following...
The most common scenario in DevOps tooling is the need to manipulate files: reading, writing, reformatting, or analyzing the data in those files. These files could be in many formats – JSON, YAML, XML, CSV, and others that are probably familiar to us. They are used to configure both local services and to interact with our cloud network provider.
In this lesson, we’ll cover the basics of reading and writing entire files.
Reading local files
Let's start by reading a configuration file on a local disk by using the os.Readfile() function:
The ReadFile() method reads the location from its function parameter and returns that file's content. That return value is then stored in the data variable. An error is returned if the file cannot be read.
ReadFile() is a helper function that calls os.Open() and retrieves an io.Reader. The io.ReadAll() function is used to read the entire content of io.Reader. ...