Ensure consistent error handling and improve resource cleanup across widgets and APIs.

This commit is contained in:
2026-01-01 12:10:33 +01:00
parent af5a39ef75
commit 2a66278cae
9 changed files with 90 additions and 48 deletions

View File

@@ -11,6 +11,8 @@ import (
const apiBaseURL = "https://newsapi.org/v2/top-headlines"
var forbiddenStrings = []string{"\r", "\\r", "\ufeff", "\u00A0"}
type configFile struct {
News newsConfig
}
@@ -65,7 +67,12 @@ func FetchNews() News {
Status: err.Error(),
}
}
defer resp.Body.Close()
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
return
}
}(resp.Body)
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return News{
@@ -75,7 +82,7 @@ func FetchNews() News {
news := News{}
err = json.Unmarshal([]byte(strings.ReplaceAll(strings.ReplaceAll(string(respBody), "\r", ""), "\u00A0", "")), &news)
err = json.Unmarshal([]byte(removeForbiddenStrings(string(respBody))), &news)
if err != nil {
log.Fatal(err)
@@ -83,3 +90,11 @@ func FetchNews() News {
return news
}
func removeForbiddenStrings(s string) string {
result := s
for _, forbidden := range forbiddenStrings {
result = strings.ReplaceAll(result, forbidden, "")
}
return result
}