-
Notifications
You must be signed in to change notification settings - Fork 178
/
write.go
45 lines (37 loc) · 1.03 KB
/
write.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package io
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
// WriteFile writes a byte array to the file at the given path.
// This method will also create the directory and file as needed.
func WriteFile(path string, data []byte) error {
err := os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
return fmt.Errorf("could not create output dir: %w", err)
}
err = ioutil.WriteFile(path, data, 0644)
if err != nil {
return fmt.Errorf("could not write file: %w", err)
}
return nil
}
// WriteText writes a byte array to the file at the given path.
func WriteText(path string, data []byte) error {
err := ioutil.WriteFile(path, data, 0644)
if err != nil {
return fmt.Errorf("could not write file: %w", err)
}
return nil
}
// WriteJSON marshals the given interface into JSON and writes it to the given path
func WriteJSON(path string, data interface{}) error {
bz, err := json.MarshalIndent(data, "", " ")
if err != nil {
return fmt.Errorf("could not marshal json: %w", err)
}
return WriteFile(path, bz)
}