-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrate_csv.go
75 lines (66 loc) · 1.49 KB
/
migrate_csv.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
package main
import (
"encoding/csv"
"errors"
"io"
"log"
"os"
"strings"
)
var (
fileName string = "logins.csv"
outFileName string = "logins_processed.csv"
errInvalidEntry error = errors.New("invalid entry")
)
func main() {
inputFile, err := os.Open(fileName)
if err != nil {
log.Fatal("Could not open file", err)
}
defer inputFile.Close()
reader := csv.NewReader(inputFile)
// reader.Comma = ','
if _, err := reader.Read(); err != nil {
log.Fatal("Error reading file", err)
}
outputFile, err := os.Create(outFileName)
if err != nil {
log.Fatal("Could not open file", err)
}
defer outputFile.Close()
writer := csv.NewWriter(outputFile)
defer writer.Flush()
if err = writer.Write([]string{"url", "username", "password"}); err != nil {
log.Fatal("Could not write to output file", err)
}
for {
line, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
log.Println("Could not process input", err)
continue
}
//fmt.Println(line)
if processedRecord, err := processLine(line); err == nil {
err = writer.Write(processedRecord)
if err != nil {
log.Println("Could not write entry", err)
continue
}
}
}
}
func processLine(line []string) ([]string, error) {
if len(line) < 3 {
return nil, errInvalidEntry
}
if line[0] == "" || !strings.HasPrefix(line[0], "http") {
return nil, errInvalidEntry
}
if line[1] == "" || line[2] == "" {
return nil, errInvalidEntry
}
return []string{line[0], line[1], line[2]}, nil
}