From the course: Go for Developers: Practical Techniques for Effective Coding
Unlock this course with a free trial
Join today to access over 24,900 courses taught by industry experts.
Files - Go Tutorial
From the course: Go for Developers: Practical Techniques for Effective Coding
Files
- Before we can read a file, we need to create it. To create a new file, we can use the OS create function. The OS create function will create a new file at the specified path if one does not already exist. If the file already exists, the OS create function will erase or truncate the existing files contents. If the file exists, the OS create function will erase or truncate the existing files contents. So here we have a create function that takes a name string and a slice of bytes as a body. We can use os create with a given name to create the file. If creating the file was successful, we can defer the call to the files close method. The close method will flush the contents of the file to the disc and close it. Finally, we can write the body to the file before we return it. Next, let's write a test that confirms that the file was created and its contents are correct. First, we'll need to make sure that the file does not already exist. To do this, we can use the os.Stat function to…