Skip to content

Commit

Permalink
cache crypto prices for 5 mins
Browse files Browse the repository at this point in the history
  • Loading branch information
asim committed Mar 21, 2022
1 parent 3a63283 commit adc0061
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions crypto/handler/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,15 @@ func (c *Crypto) Price(ctx context.Context, req *pb.PriceRequest, rsp *pb.PriceR
return errors.BadRequest("crypto.price", "invalid symbol")
}

// check the cache
cached, ok := c.Cache.Get("prices:"+req.Symbol)
if ok {
rsp.Symbol = req.Symbol
rsp.Price, _ = cached.(float64)
return nil
}


uri := fmt.Sprintf("%slast/crypto/%s?apikey=%s", c.Api, req.Symbol, c.Key)

resp, err := http.Get(uri)
Expand All @@ -243,6 +252,9 @@ func (c *Crypto) Price(ctx context.Context, req *pb.PriceRequest, rsp *pb.PriceR
rsp.Symbol = req.Symbol
rsp.Price = respBody["price"].(float64)

// set the cache
c.Cache.Set("prices:"+req.Symbol, rsp.Price, time.Minute * 5)

return nil
}

Expand Down

0 comments on commit adc0061

Please sign in to comment.