-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathio_file_helper.go
51 lines (45 loc) · 1.19 KB
/
io_file_helper.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
package build
import (
"encoding/json"
"fmt"
"log"
"os"
)
func readIpTable(ipTablePath string) map[uint64]map[uint64]string {
// Read the contents of ipTable.json
file, err := os.ReadFile(ipTablePath)
if err != nil {
// handle error
fmt.Println(err)
}
// Create a map to store the IP addresses
var ipMap map[uint64]map[uint64]string
// Unmarshal the JSON data into the map
err = json.Unmarshal(file, &ipMap)
if err != nil {
// handle error
fmt.Println(err)
}
return ipMap
}
// make sure the file is uptodate
var fileUpToDataSet = make(map[string]struct{})
func attachLineToFile(filePath string, line string) error {
if _, exist := fileUpToDataSet[filePath]; !exist {
if delErr := os.Remove(filePath); delErr != nil && !os.IsNotExist(delErr) {
log.Panic(delErr)
}
fileUpToDataSet[filePath] = struct{}{}
}
// 以追加模式打开文件,如果文件不存在则创建
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close() // 确保函数结束时关闭文件
// 写入文件的内容,附加一个换行符
if _, err := file.WriteString(line + "\n"); err != nil {
return err
}
return nil
}