-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.go
More file actions
85 lines (69 loc) · 1.58 KB
/
Copy pathstorage.go
File metadata and controls
85 lines (69 loc) · 1.58 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
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
package main
import (
"encoding/csv"
"fmt"
"os"
"strconv"
)
type CompanyStorage interface {
GetAll() []Company
Count() int
}
type FileCompanyStorage struct {
companies []Company
}
func NewFileCompanyStorage(filePath string) (*FileCompanyStorage, error) {
companies, err := loadCompaniesFromCSV(filePath)
if err != nil {
return nil, err
}
return &FileCompanyStorage{
companies: companies,
}, nil
}
func (s *FileCompanyStorage) GetAll() []Company {
return s.companies
}
func (s *FileCompanyStorage) Count() int {
return len(s.companies)
}
func loadCompaniesFromCSV(filePath string) ([]Company, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("cannot open companies file: %w", err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = -1
reader.TrimLeadingSpace = true
rows, err := reader.ReadAll()
if err != nil {
return nil, fmt.Errorf("cannot read CSV file: %w", err)
}
if len(rows) < 2 {
return []Company{}, nil
}
var companies []Company
for i, row := range rows[1:] {
if len(row) < 10 {
return nil, fmt.Errorf("row %d has invalid column count", i+2)
}
id, err := strconv.Atoi(row[0])
if err != nil {
return nil, fmt.Errorf("row %d has invalid id: %w", i+2, err)
}
companies = append(companies, Company{
ID: id,
CompanyName: row[1],
INN: row[2],
KPP: row[3],
OGRN: row[4],
OKPO: row[5],
LegalForm: row[6],
LegalAddress: row[7],
Status: row[8],
InclusionDate: row[9],
})
}
return companies, nil
}