-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
71 lines (61 loc) · 1.43 KB
/
main.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
package main
import (
"context"
"fmt"
"io"
"net/http"
"time"
)
func main() {
processarCep("89201300")
}
func processarCep(cep string) {
ch := make(chan string)
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
go BrasilApi(ctx, ch, cep)
go ViaCep(ctx, ch, cep)
select {
case resultado := <-ch:
println(resultado)
case <-ctx.Done():
println("O tempo de execução da requisição foi excedido.")
}
}
func ViaCep(ctx context.Context, ch chan string, cep string) (*string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "https://viacep.com.br/ws/"+cep+"/json/", nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
data := string(body)
ch <- fmt.Sprintf("ViaCep - Resultado: %s", data)
return &data, nil
}
func BrasilApi(ctx context.Context, ch chan string, cep string) (*string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "https://brasilapi.com.br/api/cep/v1/"+cep, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
data := string(body)
ch <- fmt.Sprintf("BrasilAPI - Resultado: %s", body)
return &data, nil
}