2023-12-09 14:21:28 -06:00

53 lines
1.1 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
)
func FileExists(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}
func ReadFile(path string) ([]byte, error) {
var output []byte
if !FileExists(path) {
return []byte{}, fmt.Errorf("Unable to read file, file does not exist: %s", path)
}
output, err := os.ReadFile(path)
if err != nil {
return []byte{}, fmt.Errorf("Unable to read file, %v: %s", err, path)
}
return output, nil
}
func WriteFile(path string, data []byte) (int, error) {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return 0, fmt.Errorf("Unable to create parent directory, %v: %s", err, dir)
}
fh, err := os.Create(path)
if err != nil {
return 0, fmt.Errorf("Unable to open file for writing, %v: %s", err, path)
}
defer fh.Close()
bs, err := fh.Write(data)
if err != nil {
return 0, fmt.Errorf("Unable to write file, %v: %s", err, path)
}
if err := fh.Sync(); err != nil {
return 0, fmt.Errorf("Unable to sync file to disk, %v: %s", err, path)
}
return bs, nil
}