-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsv.go
102 lines (81 loc) · 1.72 KB
/
tsv.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package tsv
import (
"encoding/csv"
"errors"
"fmt"
"os"
"strings"
"time"
)
type TsvLog struct {
headers []string
fileName string
timeFormat string
tz *time.Location
writer *csv.Writer
tsvFile *os.File
}
func (log *TsvLog) getOrCreateFile() {
_, err := os.Stat(log.fileName)
creatingNewFile := os.IsNotExist(err)
log.tsvFile, err = os.OpenFile(log.fileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
fmt.Println(err)
}
log.writer = csv.NewWriter(log.tsvFile)
log.writer.Comma = '\t'
if creatingNewFile {
log.writer.Write(log.headers)
}
}
func Create(params ...string) *TsvLog {
headers := strings.Fields("ts " + params[0])
path := params[1]
format := params[2]
zone := "UTC"
if len(params) > 3 && params[3] != "" {
zone = params[3]
}
tz, err := time.LoadLocation(zone)
if err != nil {
panic(fmt.Sprintf("invalid time zone %v", zone))
}
log := TsvLog{
headers: headers,
fileName: path,
timeFormat: format,
tz: tz}
return &log
}
func (log *TsvLog) Add(data []string) error {
var err error
if len(data) != len(log.headers)-1 {
err = errors.New("csv data length doesnt match header length")
} else {
log.getOrCreateFile()
log.writer.Write(append([]string{time.Now().In(log.tz).Format(log.timeFormat)}, data...))
log.Close()
}
return err
}
func (log *TsvLog) Read() [][]string {
file, err := os.Open(log.fileName)
if err != nil {
fmt.Println(err)
}
reader := csv.NewReader(file)
reader.Comma = '\t'
records, err2 := reader.ReadAll()
if err != nil {
fmt.Println(err2)
}
file.Close()
return records
}
func (log *TsvLog) Delete() {
os.Remove(log.fileName)
}
func (log *TsvLog) Close() {
log.writer.Flush()
log.tsvFile.Close()
}