-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
97 lines (81 loc) · 1.96 KB
/
Copy pathmain.go
File metadata and controls
97 lines (81 loc) · 1.96 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
86
87
88
89
90
91
92
93
94
95
96
97
package gopostal
import (
"errors"
"fmt"
"sync"
"time"
"github.com/celso-alexandre/gopostal/zipcode"
)
// FetchZipCode fetches zip code details using a specific provider group.
func FetchZipCode(
zipCode string,
providerGroup zipcode.ProviderGroupName,
timeout time.Duration,
) (*zipcode.ZipCodeInfo, error) {
return FetchZipCodeFromProviders(zipCode, zipcode.ProviderGroups[providerGroup], timeout)
}
// FetchZipCodeFromProviders tries multiple providers concurrently and returns the first successful result.
func FetchZipCodeFromProviders(zipCode string, providers []zipcode.ZipCodeProvider, timeout time.Duration) (*zipcode.ZipCodeInfo, error) {
var wg sync.WaitGroup
providersCount := len(providers)
resultChan := make(chan *zipcode.ZipCodeInfo, 1)
errChan := make(chan error, providersCount)
var isDoneMu sync.Mutex
isDone := false
errorsCount := 0
var errorCountMu sync.Mutex
for _, provider := range providers {
wg.Add(1)
go func(p zipcode.ZipCodeProvider) {
defer wg.Done()
info := p.GetZipCodeDetails(zipCode)
isDoneMu.Lock()
if isDone {
isDoneMu.Unlock()
return
}
isDoneMu.Unlock()
if info.Err != "" {
errChan <- errors.New(info.Err)
return
}
select {
case resultChan <- info.ZipCodeInfo:
default:
}
}(provider)
}
go func() {
wg.Wait()
close(resultChan)
close(errChan)
}()
timeoutChan := time.After(timeout)
for {
select {
case result := <-resultChan:
isDoneMu.Lock()
isDone = true
isDoneMu.Unlock()
return result, nil
case <-timeoutChan:
isDoneMu.Lock()
isDone = true
isDoneMu.Unlock()
return nil, errors.New(zipcode.ErrZipCodeTimeout)
case err := <-errChan:
errorCountMu.Lock()
errorsCount++
allFailed := errorsCount == providersCount
errorCountMu.Unlock()
if allFailed {
isDoneMu.Lock()
isDone = true
isDoneMu.Unlock()
return nil, err
} else {
fmt.Println("FetchZipCodeDetails (not yet given up) err:", err)
}
}
}
}