client.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package currency
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "time"
  8. )
  9. const (
  10. apiBaseURL = "https://v6.exchangerate-api.com/v6"
  11. userAgent = "opencost-plugins/1.0"
  12. )
  13. type httpClient interface {
  14. Do(req *http.Request) (*http.Response, error)
  15. }
  16. type exchangeRateClient struct {
  17. apiKey string
  18. httpClient httpClient
  19. timeout time.Duration
  20. }
  21. func newExchangeRateClient(apiKey string, timeout time.Duration) *exchangeRateClient {
  22. if timeout == 0 {
  23. timeout = 10 * time.Second
  24. }
  25. return &exchangeRateClient{
  26. apiKey: apiKey,
  27. httpClient: &http.Client{
  28. Timeout: timeout,
  29. },
  30. timeout: timeout,
  31. }
  32. }
  33. func (c *exchangeRateClient) fetchRates(baseCurrency string) (*exchangeRateResponse, error) {
  34. if c.apiKey == "" {
  35. return nil, fmt.Errorf("API key is required")
  36. }
  37. if baseCurrency == "" {
  38. baseCurrency = "USD"
  39. }
  40. url := fmt.Sprintf("%s/%s/latest/%s", apiBaseURL, c.apiKey, baseCurrency)
  41. req, err := http.NewRequest("GET", url, nil)
  42. if err != nil {
  43. return nil, fmt.Errorf("failed to create request: %w", err)
  44. }
  45. req.Header.Set("User-Agent", userAgent)
  46. req.Header.Set("Accept", "application/json")
  47. resp, err := c.httpClient.Do(req)
  48. if err != nil {
  49. return nil, fmt.Errorf("failed to fetch exchange rates: %w", err)
  50. }
  51. defer resp.Body.Close()
  52. if resp.StatusCode != http.StatusOK {
  53. body, _ := io.ReadAll(resp.Body)
  54. return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
  55. }
  56. body, err := io.ReadAll(resp.Body)
  57. if err != nil {
  58. return nil, fmt.Errorf("failed to read response body: %w", err)
  59. }
  60. var response exchangeRateResponse
  61. if err := json.Unmarshal(body, &response); err != nil {
  62. return nil, fmt.Errorf("failed to parse response: %w", err)
  63. }
  64. if response.Result != "success" {
  65. return nil, fmt.Errorf("API returned error result: %s", response.Result)
  66. }
  67. if len(response.ConversionRates) == 0 {
  68. return nil, fmt.Errorf("no conversion rates returned")
  69. }
  70. return &response, nil
  71. }