-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
120 lines (98 loc) · 2.5 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/adrianowsh/go-multithreading/dto"
)
const url_viacep = "https://viacep.com.br/ws"
const url_brasilapi = "https://brasilapi.com.br/api/cep/v1"
const time_to_request = 1 * time.Second
func main() {
chViaCep := make(chan string)
chBrasilApi := make(chan string)
ctx, cancel := context.WithTimeout(context.Background(), time_to_request)
defer cancel()
go func(ch chan<- string) {
resultViaCep, err := getResultViaCep(ctx, "06401015")
if err != nil {
log.Fatalln("timeout viacep", err)
}
ch <- fmt.Sprintf("brasil via cep => %s", resultViaCep)
}(chViaCep)
go func(ch chan<- string) {
resultBrasilApi, err := getResultBrasilApi(ctx, "06401015'")
if err != nil {
log.Fatalln("timeout brasilapi", err)
}
ch <- fmt.Sprintf("brasil api => %s", resultBrasilApi)
}(chBrasilApi)
select {
case respViaCep := <-chViaCep:
println("viacep api -> ", respViaCep)
case respBrasilApi := <-chBrasilApi:
println("brasil api -> ", respBrasilApi)
case <-ctx.Done():
println("context timeout")
}
}
func getViaCepAPi(ctx context.Context, cep string) (*dto.ViaCep, error) {
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/%s/json", url_viacep, cep), nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
var result dto.ViaCep
err = json.Unmarshal([]byte(body), &result)
if err != nil {
return nil, err
}
return &result, nil
}
func getBrasilApi(ctx context.Context, cep string) (*dto.BrasilApi, error) {
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/%s", url_brasilapi, cep), nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
var result dto.BrasilApi
err = json.Unmarshal([]byte(body), &result)
if err != nil {
return nil, err
}
return &result, nil
}
func getResultViaCep(ctx context.Context, cep string) (string, error) {
resp, err := getViaCepAPi(ctx, cep)
if err != nil {
return "", err
}
jsonResult, _ := json.Marshal(resp)
return string(jsonResult), nil
}
func getResultBrasilApi(ctx context.Context, cep string) (string, error) {
resp, err := getBrasilApi(ctx, cep)
if err != nil {
return "", err
}
jsonResult, _ := json.Marshal(resp)
return string(jsonResult), nil
}