This commit is contained in:
2026-04-20 21:29:22 +02:00
parent 53dd49612d
commit 89fc0119f3
25 changed files with 3744 additions and 134 deletions
+75
View File
@@ -0,0 +1,75 @@
package finnhub
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
const baseURL = "https://finnhub.io/api/v1"
type Client struct {
apiKey string
http *http.Client
}
type NewsItem struct {
ID int `json:"id"`
Category string `json:"category"`
Datetime int64 `json:"datetime"`
Headline string `json:"headline"`
Related string `json:"related"`
Source string `json:"source"`
URL string `json:"url"`
Summary string `json:"summary"`
}
func New(apiKey string) *Client {
return &Client{
apiKey: apiKey,
http: &http.Client{Timeout: 10 * time.Second},
}
}
func (c *Client) CompanyNews(symbol, from, to string) ([]NewsItem, error) {
url := fmt.Sprintf("%s/company-news?symbol=%s&from=%s&to=%s&token=%s",
baseURL, symbol, from, to, c.apiKey)
return c.fetchNews(url)
}
func (c *Client) MarketNews() ([]NewsItem, error) {
url := fmt.Sprintf("%s/news?category=general&token=%s", baseURL, c.apiKey)
return c.fetchNews(url)
}
func (c *Client) Ping() error {
url := fmt.Sprintf("%s/news?category=general&minId=999999999&token=%s", baseURL, c.apiKey)
resp, err := c.http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return fmt.Errorf("invalid API key (HTTP %d)", resp.StatusCode)
}
return nil
}
func (c *Client) fetchNews(url string) ([]NewsItem, error) {
resp, err := c.http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("finnhub: HTTP %d", resp.StatusCode)
}
var items []NewsItem
if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
return nil, err
}
return items, nil
}