101 lines
1.8 KiB
Go
101 lines
1.8 KiB
Go
package news
|
|
|
|
import (
|
|
"ArinDash/config"
|
|
"encoding/json"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
const apiBaseURL = "https://newsapi.org/v2/top-headlines"
|
|
|
|
var forbiddenStrings = []string{"\r", "\\r", "\ufeff", "\u00A0"}
|
|
|
|
type configFile struct {
|
|
News newsConfig
|
|
}
|
|
|
|
type newsConfig struct {
|
|
ApiKey string
|
|
Sources string
|
|
}
|
|
|
|
type News struct {
|
|
Status string `json:"status"`
|
|
TotalResults int `json:"totalResults"`
|
|
Articles []Article `json:"articles"`
|
|
}
|
|
|
|
type Article struct {
|
|
Source Source `json:"source"`
|
|
Author string `json:"author"`
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
URL string `json:"url"`
|
|
URLToImage string `json:"urlToImage"`
|
|
PublishedAt string `json:"publishedAt"`
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
type Source struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
func FetchNews() News {
|
|
cfg := &configFile{}
|
|
config.LoadConfig(cfg)
|
|
client := &http.Client{}
|
|
|
|
if cfg.News.ApiKey == "" {
|
|
return News{
|
|
Status: "No API key provided",
|
|
}
|
|
}
|
|
|
|
req, err := http.NewRequest("GET", apiBaseURL+"?sources="+cfg.News.Sources+"&pageSize=100&apiKey="+cfg.News.ApiKey, nil)
|
|
if err != nil {
|
|
return News{
|
|
Status: err.Error(),
|
|
}
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return News{
|
|
Status: err.Error(),
|
|
}
|
|
}
|
|
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{
|
|
Status: err.Error(),
|
|
}
|
|
}
|
|
|
|
news := News{}
|
|
|
|
err = json.Unmarshal([]byte(removeForbiddenStrings(string(respBody))), &news)
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
return news
|
|
}
|
|
|
|
func removeForbiddenStrings(s string) string {
|
|
result := s
|
|
for _, forbidden := range forbiddenStrings {
|
|
result = strings.ReplaceAll(result, forbidden, "")
|
|
}
|
|
return result
|
|
}
|