Add News widget and integrate NewsAPI for live updates
This commit is contained in:
77
apis/newsapi/main.go
Normal file
77
apis/newsapi/main.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package news
|
||||
|
||||
import (
|
||||
"ArinDash/config"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const apiBaseURL = "https://newsapi.org/v2/top-headlines"
|
||||
|
||||
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{}
|
||||
|
||||
req, err := http.NewRequest("GET", apiBaseURL+"?sources="+cfg.News.Sources+"&pageSize=100&apiKey="+cfg.News.ApiKey, nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return News{
|
||||
Status: err.Error(),
|
||||
}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return News{
|
||||
Status: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
news := News{}
|
||||
|
||||
err = json.Unmarshal([]byte(strings.ReplaceAll(strings.ReplaceAll(string(respBody), "\r", ""), "\u00A0", "")), &news)
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
return news
|
||||
}
|
||||
Reference in New Issue
Block a user