-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdolarpy.go
103 lines (84 loc) · 2.46 KB
/
dolarpy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package dolarpy
import (
"encoding/json"
"fmt"
"net/http"
)
// APIData represents the structure of the API response
type APIData struct {
Dolarpy map[string]map[string]float64 `json:"dolarpy"`
}
// getAPIData retrieves the API data from the remote server
func getAPIData() (*APIData, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://dolar.melizeche.com/api/1.0/", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("User-Agent", "DolarpyWrapper/Golang")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
var data APIData
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
return &data, nil
}
// Reference returns the referential exchange rate from BCP
func Reference() (float64, error) {
data, err := getAPIData()
if err != nil {
return 0, fmt.Errorf("failed to get API data: %w", err)
}
return data.Dolarpy["bcp"]["referencial_diario"], nil
}
// Providers returns a list of available providers
func Providers() ([]string, error) {
data, err := getAPIData()
if err != nil {
return nil, fmt.Errorf("failed to get API data: %w", err)
}
providers := make([]string, 0, len(data.Dolarpy))
for key := range data.Dolarpy {
providers = append(providers, key)
}
return providers, nil
}
// Purchase returns the purchase exchange rate from the specified provider
// If provider is empty, returns the rate from BCP
func Purchase(provider string) (float64, error) {
data, err := getAPIData()
if err != nil {
return 0, fmt.Errorf("failed to get API data: %w", err)
}
rate := data.Dolarpy["bcp"]["compra"]
if provider != "" {
rate = data.Dolarpy[provider]["compra"]
}
return rate, nil
}
// Sale returns the sale exchange rate from the specified provider
// If provider is empty, returns the rate from BCP
func Sale(provider string) (float64, error) {
data, err := getAPIData()
if err != nil {
return 0, fmt.Errorf("failed to get API data: %w", err)
}
rate := data.Dolarpy["bcp"]["venta"]
if provider != "" {
rate = data.Dolarpy[provider]["venta"]
}
return rate, nil
}
// All returns all available exchange rates from all providers
func All() (map[string]map[string]float64, error) {
data, err := getAPIData()
if err != nil {
return nil, fmt.Errorf("failed to get API data: %w", err)
}
return data.Dolarpy, nil
}