// Append a file. alert.Exit on failure func Append(filename string, label string) *os.File { file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) if err != nil { alert.Exit("Can't append " + label + " file: " + filename + ", " + err.Error()) } return file }
// ReadFile reads a file and returns the contents as a string. alert.Exit on failure. func ReadFile(filename string, label string) string { bytes, err := ioutil.ReadFile(filename) if err != nil { alert.Exit("Can't read " + label + " file: " + filename + ", " + err.Error()) } return string(bytes) }
// Create a file. alert.Exit on failure. func Create(filename string, label string) *os.File { file, err := os.Create(filename) if err != nil { alert.Exit("Can't create " + label + " file: " + filename + ", " + err.Error()) } return file }
// Open a file. alert.Exit on failure. func Open(filename string) *os.File { file, err := os.Open(filename) if err != nil { alert.Exit("Can't open file: " + filename + ", " + err.Error()) } return file }
// ParseFloat64 parses a string and returns a float64. On failure it displays // an error message and calls exit. func ParseFloat64(str string) float64 { result, err := strconv.ParseFloat(str, 64) if err != nil { alert.Exit("Failed to parse float64: " + str + ", " + err.Error()) } return result }
// ParseUint32 parses a string and returns a uint32. On failure it displays // an error message and calls exit. func ParseUint32(str string) uint32 { result, err := strconv.ParseUint(str, 10, 32) if err != nil { alert.Exit("Failed to parse uint32: " + str + ", " + err.Error()) } return uint32(result) }
// ReadYAML reads a YAML file into an arbitrary structure. func ReadYAML(filename string, config interface{}) { data := ReadFile(filename, "YAML") err := yaml.Unmarshal([]byte(data), config) if err != nil { alert.Exit("Can't unmarshal " + filename + " into config: " + err.Error()) } }
// WriteFile writes a string to file. If a file with that name exists, // it will overwrite it. alert.Exit on failure. func WriteFile(filename, body, label string) { err := ioutil.WriteFile(filename, []byte(body), 0644) if err != nil { alert.Exit("Can't create " + label + " file: " + filename + ", " + err.Error()) } }