Hi all,
I’m a few hours into learning Go, and I’m loving it. My programming history has been C++ > Java > Groovy > Go. I mostly use programming for simple tooling, so I have to admit I’ve not reached pro at any of them, but I do try to take an interest in good habits/best practice.
With that in mind I would like to understand the motions you guys would go through if you were to refactor my rather basic project.
In this example I’m taking a files contents (called LICENSE) and adding it to my go source code as a header.
// USAGE: go run main.go -lp=/some/file.txt -sp=/a/directory/with/go/files
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var lpPtr string
var spPtr string
func init() {
// Create some flags for the user
flag.StringVar(&lpPtr, "license_path", "LICENSE", "path to LICENSE file")
flag.StringVar(&lpPtr, "lp", "LICENSE", "path to LICENSE file (Short hand)")
flag.StringVar(&spPtr, "source_path", "demo.txt", "path to source file")
flag.StringVar(&spPtr, "sp", "demo.txt", "path to source file (Short hand)")
flag.Parse()
fmt.Println("License Path:", lpPtr)
fmt.Println("Source Path:", spPtr)
}
var licenseData []byte
func main() {
// Load the LICENSE into memory
var err error
licenseData, err = ioutil.ReadFile(lpPtr)
check(err)
// Walk the directory structure, calling license at each node
err = filepath.Walk(spPtr, license)
check(err)
}
// Check for error and if error, then panic
func check(e error) {
if e != nil {
panic(e)
}
}
// license is called for each file visited by Walk. If its not a directory
// and a file with suffix '.go' then it will add the License via licenseWriter
func license(path string, f os.FileInfo, err error) error {
if !f.IsDir() {
if strings.HasSuffix(path, ".go") {
fmt.Printf("Filename: %s \n", path)
addLicenseHeader(path, licenseData)
}
}
return nil
}
func addLicenseHeader(path string, data []byte) {
//err =: ioutil.WriteFile(path, data, 0644)
//check(err)
fmt.Printf("License added to: %s \n", path)
}
I realise there’s a lot wrong with this. Global scope vars as one example, but I’m keen to know what you think (be nice ).
I would also like to better understand testing in Go, so any pointers around that would be welcomed too!
Thank you kindly in advance!