-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmovies.go
97 lines (89 loc) · 2.03 KB
/
movies.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
package logic
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"os"
"os4gophers/domain"
"sync"
)
func LoadMoviesFromFile(fileName string) ([]domain.Movie, error) {
const (
concurrency = 5
)
var (
movies []domain.Movie
waitGroup = new(sync.WaitGroup)
workQueue = make(chan string)
mutex = &sync.Mutex{}
errChan = make(chan error, concurrency)
)
go func() {
moviesFile, err := os.Open(fileName)
if err != nil {
errChan <- err
close(workQueue)
return
}
defer func(moviesFile *os.File) {
err := moviesFile.Close()
if err != nil {
errChan <- err
}
}(moviesFile)
scanner := bufio.NewScanner(moviesFile)
for scanner.Scan() {
workQueue <- scanner.Text()
}
if err := scanner.Err(); err != nil {
errChan <- err
}
close(workQueue)
}()
for i := 0; i < concurrency; i++ {
waitGroup.Add(1)
go func(workQueue chan string, waitGroup *sync.WaitGroup) {
defer waitGroup.Done()
for entry := range workQueue {
movieRaw := domain.MovieRaw{}
err := json.Unmarshal([]byte(entry), &movieRaw)
if err != nil {
errChan <- err
continue
}
movie := func(movieRaw domain.MovieRaw) domain.Movie {
return domain.Movie{
Title: movieRaw.Title,
Year: movieRaw.Year,
RunningTime: movieRaw.Info.RunningTime,
ReleaseDate: movieRaw.Info.ReleaseDate,
Rating: movieRaw.Info.Rating,
Genres: movieRaw.Info.Genres,
Actors: movieRaw.Info.Actors,
Directors: movieRaw.Info.Directors,
}
}(movieRaw)
mutex.Lock()
movies = append(movies, movie)
mutex.Unlock()
}
}(workQueue, waitGroup)
}
waitGroup.Wait()
close(errChan)
// Collect errors
var errs []error
for err := range errChan {
errs = append(errs, err)
}
if len(errs) > 0 {
errorMsg := "Errors occurred while loading movies:"
for _, err := range errs {
errorMsg += "\n- " + err.Error()
}
return movies, errors.New(errorMsg)
}
fmt.Printf("🟦 Movies loaded from file: %d \n", len(movies))
return movies, nil
}