Skip to content

Commit

Permalink
use context for http requests in coingecko/kraken
Browse files Browse the repository at this point in the history
  • Loading branch information
chris124567 committed Jan 15, 2025
1 parent 7eb11c4 commit 1b2248c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
6 changes: 3 additions & 3 deletions exchangerates/coingecko.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ func newcoinGeckoAPI(apiKey string) *coinGeckoAPI {
type coinGeckoPriceResponse map[string]map[string]float64

// See https://docs.coingecko.com/reference/simple-price
func (k *coinGeckoAPI) ticker(currency, token string) (float64, error) {
func (k *coinGeckoAPI) ticker(ctx context.Context, currency, token string) (float64, error) {
currency = strings.ToLower(currency)
token = strings.ToLower(token)

request, err := http.NewRequest(http.MethodGet, fmt.Sprintf("https://api.coingecko.com/api/v3/simple/price?vs_currencies=%s&ids=%s", currency, token), nil)
request, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://api.coingecko.com/api/v3/simple/price?vs_currencies=%s&ids=%s", currency, token), nil)
if err != nil {
return 0, err
}
Expand Down Expand Up @@ -98,7 +98,7 @@ func (c *coinGecko) Start(ctx context.Context) {
select {
case <-ticker.C:
c.mu.Lock()
c.rate, c.err = c.client.ticker(c.currency, c.token)
c.rate, c.err = c.client.ticker(ctx, c.currency, c.token)
c.mu.Unlock()
case <-ctx.Done():
c.mu.Lock()
Expand Down
11 changes: 8 additions & 3 deletions exchangerates/kraken.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,14 @@ func newKrakenAPI() *krakenAPI {
}

// See https://docs.kraken.com/api/docs/rest-api/get-ticker-information
func (k *krakenAPI) ticker(pair string) (float64, error) {
func (k *krakenAPI) ticker(ctx context.Context, pair string) (float64, error) {
pair = strings.ToUpper(pair)
response, err := k.client.Get("https://api.kraken.com/0/public/Ticker?pair=" + url.PathEscape(pair))

request, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.kraken.com/0/public/Ticker?pair="+url.PathEscape(pair), nil)
if err != nil {
return 0, err
}
response, err := k.client.Do(request)
if err != nil {
return 0, err
}
Expand Down Expand Up @@ -96,7 +101,7 @@ func (k *kraken) Start(ctx context.Context) {
select {
case <-ticker.C:
k.mu.Lock()
k.rate, k.err = k.client.ticker(k.pair)
k.rate, k.err = k.client.ticker(ctx, k.pair)
k.mu.Unlock()
case <-ctx.Done():
k.mu.Lock()
Expand Down

0 comments on commit 1b2248c

Please sign in to comment.