-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileWriter.go
More file actions
49 lines (38 loc) · 1.04 KB
/
fileWriter.go
File metadata and controls
49 lines (38 loc) · 1.04 KB
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
package main
import (
"os"
"strings"
"sync"
"github.com/uber-go/zap"
)
var writeLock sync.Mutex
// writeToFile writes string content to file
func writeToFile(filename, content string) {
writeLock.Lock()
defer writeLock.Unlock()
logger.Info("Writing to", zap.String("filename", filename), zap.String("content", content))
if strings.TrimSpace(filename) == "" || strings.TrimSpace(content) == "" {
logger.Error("Writing to", zap.String("filename", filename), zap.String("reason", "failed because content or filename is empty(probably nothing to write)"))
return
}
// ensure path is ready
folderPath := strings.Split(filename, "/")
folderPath = folderPath[:len(folderPath)-1]
folderPathS := strings.Join(folderPath, "/")
err := os.MkdirAll(folderPathS, 0777)
if err != nil {
panic(err)
}
file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
_, err = file.WriteString(content + "\n")
if err != nil {
panic(err)
}
err = file.Close()
if err != nil {
panic(err)
}
}