I'm beginning to learn Go. I've decided to write some file utilities to help me with some bigger projects I intend to write. Coming from mainly a Python background, I'm sure there are plenty of stylistic and efficiency improvements to be made. I'm looking for general feedback, as I want to kick bad habits to the curb before they set it. Feedback such as:
- Error Reporting
- Use of
defer
inappendContent
function - Testing Functions: Are there any libraries to help accomplish this, like how Python has
unittest
?
I use more comments than I usually would when programming because I'm still learning the language. The Usage:
comments help me remember why I'm importing these libraries. Besides the specifically requested feedback, any and all criticism is welcome and appreciated!
Utilities
package main
import (
"fmt" // Usage: Printing errors and content of the files
"io/ioutil" // Usage: Reading and writing files
"os" // Usage: Opening files and appending to them
)
func main() {
testFunctions()
}
func testFunctions() {
/*
This method is solely for the purpose of testing the below methods
*/
writeContent("test.txt", "Test Content")
fmt.Println(getContent("test.txt"))
appendContent("test.txt", "Test Content 2")
fmt.Println(getContent("test.txt"))
}
func getContent(file string) string {
/*
Gets the content from the passed `file`
*/
content, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return "[NOT CONTENT]: AN ERROR OCCURED"
}
return string(content)
}
func writeContent(file string, content string) {
/*
Writes the passed `content`, creating a new file at `file`
*/
formattedContent := []byte(content)
err := ioutil.WriteFile(file, formattedContent, 0777)
if err != nil {
fmt.Println(err)
}
}
func appendContent(file string, content string) {
/*
Appends the passed `content` to the end of the passed `file`
*/
fileToAppend, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
defer fileToAppend.Close()
_, err = fileToAppend.WriteString(content)
if err != nil {
panic(err)
}
}