-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_temperature.go
108 lines (94 loc) · 2.39 KB
/
get_temperature.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
package get_temperature
import (
"context"
"encoding/json"
"fmt"
"github.com/aluferraz/go-expert-cep-cloudrun/internal/entity/zipcode"
"io"
"net/http"
"net/url"
)
type AddressResponse struct {
Localidade string `json:"localidade"`
}
type InputDTO struct {
WeatherApiKey string
WeatherApiUrl string
ApiCepUrl string
Zipcode zipcode.Zipcode
}
type OutputDTO struct {
City string `json:"-"`
CelsiusTemp float64 `json:"temp_C"`
FahrenheitTemp float64 `json:"temp_F"`
KelvinTemp float64 `json:"temp_K"`
}
type UseCase struct {
ctx *context.Context
client *http.Client
}
func NewUseCase(
ctx *context.Context,
client *http.Client,
) UseCase {
return UseCase{
ctx: ctx,
client: client,
}
}
func getCityFromZipCode(apiUrl string, zipcode string) (string, error) {
// "https://viacep.com.br/ws/%s/json/"
resp, err := http.Get(fmt.Sprintf(apiUrl, zipcode))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var addressResponse AddressResponse
err = json.Unmarshal(body, &addressResponse)
if err != nil {
return "", err
}
return addressResponse.Localidade, nil
}
func getTemperatureFromCity(apiUrl string, apikey string, city string) (float64, error) {
//"http://api.weatherapi.com/v1/current.json?key=%s&q=%s"
url := fmt.Sprintf(apiUrl, url.QueryEscape(apikey), url.QueryEscape(city))
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer func(Body io.ReadCloser) {
Body.Close()
}(resp.Body)
body, _ := io.ReadAll(resp.Body)
var weatherResponse map[string]interface{}
err = json.Unmarshal(body, &weatherResponse)
if err != nil {
return 0, err
}
temperatureData, ok := weatherResponse["current"].(map[string]interface{})
if !ok {
return 0, fmt.Errorf("Invalid temperature data")
}
return temperatureData["temp_c"].(float64), nil
}
func (uc *UseCase) Execute(inputDto InputDTO) (OutputDTO, error) {
var err error
city, err := getCityFromZipCode(inputDto.ApiCepUrl, inputDto.Zipcode.Zipcode)
result := OutputDTO{}
if err != nil {
return result, err
}
if city != "" {
celsiusTemp, err := getTemperatureFromCity(inputDto.WeatherApiUrl, inputDto.WeatherApiKey, city)
if err != nil {
return result, err
}
result.CelsiusTemp = celsiusTemp
}
result.City = city
result.FahrenheitTemp = (result.CelsiusTemp * 1.8) + 32
result.KelvinTemp = result.CelsiusTemp + 273
return result, nil
}