-
Notifications
You must be signed in to change notification settings - Fork 1
/
cep_service.go
73 lines (66 loc) · 1.5 KB
/
cep_service.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
package cep
import (
"fmt"
"time"
"github.com/guionardo/go-gstools/tools"
)
type CEPService struct {
repository CEPRepository
}
var apis [4]CEPAPIProvider = [4]CEPAPIProvider{
&CEPCorreiosAPI{},
&CEPAPIViaCep{},
&CEPAPICep{},
&CEPAPIBrasilAPI{},
}
func NewCEPService(repository CEPRepository) *CEPService {
return &CEPService{
repository: repository,
}
}
func NewSQliteCEPService(connectionString string) (*CEPService, error) {
repo, err := NewCEPRepositorySQLite(connectionString)
if err == nil {
return NewCEPService(repo), nil
}
return nil, err
}
func (c *CEPService) GetCEP(cep string) (*CEP, error) {
cep = tools.JustNumbers(cep)
cepData, err := c.repository.GetCEP(cep)
if err == nil && cepData != nil && cepData.DataRequisicao.After(time.Now().Add(-24*time.Hour*30)) {
return cepData, nil
}
var errors []error
ch := make(chan *CEP)
errorChan := make(chan error)
for _, api := range apis {
go func(api CEPAPIProvider) {
cepDataReq, err := api.GetCEP(cep)
if err == nil {
ch <- cepDataReq
} else {
errorChan <- err
}
}(api)
}
for i := 0; i < len(apis); i++ {
select {
case res := <-ch:
if res != nil {
res.DataRequisicao = time.Now()
res.CheckTipoLogradouro()
err = c.repository.SaveCEP(res)
return res, err
}
case err := <-errorChan:
if err != nil {
errors = append(errors, err)
}
}
}
if len(errors) == len(apis) {
return nil, fmt.Errorf("Nenhuma API disponível")
}
return nil, fmt.Errorf("Nenhuma API retornou dados")
}