Improve error handling and include User-Agent

This commit is contained in:
raul 2024-05-08 11:14:11 +02:00
parent 53e4b1acf9
commit cc49c07b1b
1 changed files with 26 additions and 10 deletions

View File

@ -25,11 +25,14 @@ type root struct {
} `json:"root"` } `json:"root"`
} }
func main() { func client() {
jsonData := getJSON() jsonData, err := getJSON()
if err != nil {
log.Fatal(err)
}
textBytes := []byte(jsonData) textBytes := []byte(jsonData)
aemetRequest := root{} aemetRequest := root{}
err := json.Unmarshal(textBytes, &aemetRequest) err = json.Unmarshal(textBytes, &aemetRequest)
if err != nil { if err != nil {
log.Fatalf("Error occurred unmarshalling data: %v\n", err) log.Fatalf("Error occurred unmarshalling data: %v\n", err)
} }
@ -40,27 +43,40 @@ func main() {
fmt.Printf("Temperatura mínima: %v°C\n", aemetRequest.Base.Prediccion.Dia[0].Temperatura.Minima) fmt.Printf("Temperatura mínima: %v°C\n", aemetRequest.Base.Prediccion.Dia[0].Temperatura.Minima)
} }
func getJSON() string { func getJSON() (s string, err error) {
resp, err := http.Get("https://www.aemet.es/xml/municipios/localidad_46250.xml") client := &http.Client{}
req, err := http.NewRequest("GET", "https://www.aemet.es/xml/municipios/localidad_46250.xml", nil)
if err != nil { if err != nil {
log.Fatalf("Error occurred pulling data: %v\n", err) e := fmt.Errorf("Error occurred pulling data: %v\n", err)
return "", e
}
req.Header.Set("User-Agent", "AEMET-Client/1.0 (https://git.bulgariu.xyz/raul/aemet)")
resp, err := client.Do(req)
if err != nil {
e := fmt.Errorf("Error occurred pulling data: %v\n", err)
return "", e
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
log.Fatalf("Error occurred accessing website: %v\n", err) e := fmt.Errorf("Error occurred accessing upstream website: %v\n", resp.Status)
return "", e
} }
data, err := io.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
log.Fatalf("Error occurred reading data: %v\n", err) e := fmt.Errorf("Error occurred reading data: %v\n", err)
return "", e
} }
xml := strings.NewReader(string(data)) xml := strings.NewReader(string(data))
json, err := xj.Convert(xml) json, err := xj.Convert(xml)
if err != nil { if err != nil {
log.Fatalf("Error occurred converting XML to JSON: %v\n", err) e := fmt.Errorf("Error occurred converting XML to JSON: %v\n", err)
return "", e
} }
return json.String() return json.String(), nil
} }