La biblioteca estándar basta para una integración fiable. Rechaza respuestas no exitosas antes de decodificar y conserva la fuente, la sesión de mercado y la hora de actualización.
- Crea un cliente tipado: El ejemplo usa net/http, context y encoding/json. Envía varias monedas en una sola solicitud y añade el bearer solo cuando existe EXCHANGERATE_API_KEY.
- Llama con un timeout: Usa context.WithTimeout para que una conexión bloqueada no ocupe un trabajador indefinidamente. Reutiliza un http.Client configurado en producción.
- Maneja errores y frescura: Un 401 requiere corregir la clave; un 429 requiere reducir el tráfico. Conserva source, market_session y data_updated_at junto al tipo, y no expongas la clave en navegador o móvil.
Crea un cliente tipado
El ejemplo usa net/http, context y encoding/json. Envía varias monedas en una sola solicitud y añade el bearer solo cuando existe EXCHANGERATE_API_KEY.
package mainimport ( "context" "encoding/json" "fmt" "net/http" "log" "os" "regexp" "strings" "time")type Latest struct { Base string `json:"base"` Source string `json:"source"` MarketSession string `json:"market_session"` UpdatedAt time.Time `json:"data_updated_at"` Sources map[string]string `json:"sources"` EffectiveAt map[string]string `json:"effective_at"` Rates map[string]json.Number `json:"rates"`}func LatestRates(ctx context.Context, base string) (Latest, error) { base = strings.ToUpper(base) if !regexp.MustCompile("^[A-Z]{3}$").MatchString(base) { return Latest{}, fmt.Errorf("invalid base currency: %q", base) } url := "https://api.exchangerate.dev/v1/latest/" + base + "?symbols=EUR,GBP,JPY" req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return Latest{}, err } if key := os.Getenv("EXCHANGERATE_API_KEY"); key != "" { req.Header.Set("Authorization", "Bearer "+key) } client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} res, err := client.Do(req) if err != nil { return Latest{}, err } defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode >= 300 { return Latest{}, fmt.Errorf("exchange rate API: HTTP %s", res.Status) } var out Latest if err := json.NewDecoder(res.Body).Decode(&out); err != nil { return Latest{}, err } return out, nil}func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() latest, err := LatestRates(ctx, "USD") if err != nil { log.Fatal(err) } fmt.Println(latest.Rates["EUR"], latest.Sources["EUR"], latest.EffectiveAt["EUR"])}Llama con un timeout
go run main.goManeja errores y frescura
Un 401 requiere corregir la clave; un 429 requiere reducir el tráfico. Conserva source, market_session y data_updated_at junto al tipo, y no expongas la clave en navegador o móvil.
Programa una tarea diaria para informes o una tarea horaria para un panel. Si recibes 429, reduce la frecuencia en lugar de crear reintentos inmediatos.
- Guarda el tipo junto a su fuente y hora.
- Usa el valor para automatización y análisis.
- No lo trates como una cotización ejecutable.