/
lagoinha.go
79 lines (65 loc) · 1.8 KB
/
lagoinha.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
package lagoinha
import (
"github.com/igorhalfeld/lagoinha/internal/entity"
"github.com/igorhalfeld/lagoinha/internal/service"
"github.com/igorhalfeld/lagoinha/internal/service/apicep"
"github.com/igorhalfeld/lagoinha/internal/service/brasilapi"
"github.com/igorhalfeld/lagoinha/internal/service/viacep"
"github.com/igorhalfeld/lagoinha/pkg/errors"
)
var providers = map[string]service.Provider{
"BrasilAPI": brasilapi.New(),
"ViaCEP": viacep.New(),
"Apicep": apicep.New(),
}
// GetTotalAmountOfCepProviders returns amount of current enabled cep provivers
func GetTotalAmountOfCepProviders() int {
return len(providers)
}
func getAddress(cepRaw string, opts *GetAddressOptions, chResponse chan *entity.Cep, chError chan error) {
cep := entity.Cep{
Cep: cepRaw,
}
if !cep.IsValid() {
chError <- errors.CepNotValidError
return
}
// TODO: enhance this way of handling options
if opts != nil {
if opts.PreferenceForAPI != "" {
provider, ok := providers[opts.PreferenceForAPI]
if !ok {
chError <- errors.PreferenceProviderNotFound
return
}
c, err := provider.Request(cep.Cep)
if err != nil {
chError <- err
return
}
chResponse <- c
return
}
}
// TODO: add context.WithCancel for slower requests
for providerName := range providers {
go func(p, cv string) {
c, err := providers[p].Request(cv)
if err != nil {
chError <- err
return
}
chResponse <- c
}(providerName, cep.Cep)
}
}
type GetAddressOptions struct {
PreferenceForAPI string
}
// GetAddress - get address
func GetAddress(cepRaw string, opts *GetAddressOptions) (chan *entity.Cep, chan error) {
chResponse := make(chan *entity.Cep, GetTotalAmountOfCepProviders())
chError := make(chan error)
go getAddress(cepRaw, opts, chResponse, chError)
return chResponse, chError
}