-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfile_extensions.go
52 lines (48 loc) · 1.07 KB
/
file_extensions.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
46
47
48
49
50
51
52
package goext
import (
"encoding/json"
"errors"
"os"
)
// WriteJsonToFile writes the given object into a file.
func WriteJsonToFile(object any, outputFilePath string, indented bool) error {
var data []byte
var err error
if indented {
data, err = json.MarshalIndent(object, "", " ")
} else {
data, err = json.Marshal(object)
}
if err != nil {
return err
}
if err := os.WriteFile(outputFilePath, data, os.ModePerm); err != nil {
return err
}
return nil
}
// FileExists checks if a file exists (and it is not a directory).
func FileExists(filePath string) (bool, error) {
info, err := os.Stat(filePath)
if err == nil {
return !info.IsDir(), nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
// CopyFile is a simple file copy from source to destination.
func CopyFile(src string, dst string) (int64, error) {
srcFile, err := os.Open(src)
if err != nil {
return -1, err
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return -1, err
}
defer dstFile.Close()
return dstFile.ReadFrom(srcFile)
}