Ensure consistent error handling and improve resource cleanup across widgets and APIs.
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user