-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create new service for cryptocurrency price monitoring
- Loading branch information
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package services | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"net/http" | ||
"sync" | ||
"time" | ||
) | ||
|
||
type PriceMonitor struct { | ||
apiKey string | ||
httpClient *http.Client | ||
prices sync.Map | ||
} | ||
|
||
type CoinGeckoPrice struct { | ||
Bitcoin struct { | ||
USD float64 `json:"usd"` | ||
} `json:"bitcoin"` | ||
Ethereum struct { | ||
USD float64 `json:"ethereum"` | ||
} `json:"ethereum"` | ||
} | ||
|
||
func NewPriceMonitor(apiKey string) *PriceMonitor { | ||
return &PriceMonitor{ | ||
apiKey: apiKey, | ||
httpClient: &http.Client{ | ||
Timeout: 10 * time.Second, | ||
}, | ||
} | ||
} | ||
|
||
func (pm *PriceMonitor) StartMonitoring(checkInterval time.Duration) { | ||
ticker := time.NewTicker(checkInterval) | ||
go func() { | ||
for range ticker.C { | ||
pm.updatePrices() | ||
} | ||
}() | ||
} | ||
|
||
func (pm *PriceMonitor) updatePrices() error { | ||
url := fmt.Sprintf("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd") | ||
resp, err := pm.httpClient.Get(url) | ||
if err != nil { | ||
return fmt.Errorf("failed to fetch prices: %w", err) | ||
} | ||
defer resp.Body.Close() | ||
|
||
var prices CoinGeckoPrice | ||
if err := json.NewDecoder(resp.Body).Decode(&prices); err != nil { | ||
return fmt.Errorf("failed to decode response: %w", err) | ||
} | ||
|
||
pm.prices.Store("BTC", prices.Bitcoin.USD) | ||
pm.prices.Store("ETH", prices.Ethereum.USD) | ||
return nil | ||
} | ||
|
||
func (pm *PriceMonitor) GetPrice(cryptoID string) (float64, error) { | ||
price, ok := pm.prices.Load(cryptoID) | ||
if !ok { | ||
return 0, fmt.Errorf("price not available for %s", cryptoID) | ||
} | ||
return price.(float64), nil | ||
} |