-
Notifications
You must be signed in to change notification settings - Fork 0
/
booklist.go
87 lines (74 loc) · 1.42 KB
/
booklist.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
package booklist
import (
"encoding/csv"
"io"
"os"
"path/filepath"
"strings"
)
// Book exported
type Book struct {
Author string
Title string
Filename string
}
const (
dataFileName = "_booklist.csv"
)
// Service is exported
type Service struct {
books []*Book
}
//NewService is exported
func NewService(dataDirectory string) (*Service, error) {
books, err := loadFile(dataDirectory)
if err != nil {
return nil, err
}
return &Service{books: books}, nil
}
// GetByAuthor returns all the books by the given author.
func (s *Service) GetByAuthor(authorName string) []*Book {
var books []*Book
for _, b := range s.books {
if strings.ToLower(authorName) == strings.ToLower(b.Author) {
books = append(books, b)
}
}
return books
}
func loadFile(dataDirectory string) ([]*Book, error) {
f, err := os.Open(filepath.Join(dataDirectory, dataFileName))
if err != nil {
return nil, err
}
defer f.Close()
reader := csv.NewReader(f)
reader.ReuseRecord = true
reader.FieldsPerRecord = 0
reader.TrimLeadingSpace = true
_, err = reader.Read() // header row
if err != nil {
return nil, err
}
var readErr error
var books []*Book
for {
row, readErr := reader.Read()
if readErr != nil {
break
}
books = append(books, &Book{
Author: row[0],
Filename: row[1],
Title: row[2],
})
}
if readErr == io.EOF {
readErr = nil
}
if readErr != nil {
return nil, readErr
}
return books, nil
}