Files
fn_registry/functions/infra/http_get_json.go
T
egutierrez 9c0d24d3ef feat: funciones Go — core (cron, join_by_key, validate_struct), datascience (pivot, diff_entities), infra (http, cache, cron_ticker)
Nuevas funciones Go con tests en tres dominios:
- core: parse_cron_expr, next_cron_time, join_by_key, validate_struct_fields + tipo CronSchedule
- datascience: pivot (tabla dinámica), diff_entities (comparación de entidades)
- infra: http_get_json, http_post_json, http_download_file, cache_to_sqlite, cron_ticker

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:11:12 +02:00

57 lines
1.4 KiB
Go

package infra
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// HttpGetJSON realiza un GET request a url y parsea la respuesta como JSON.
// Agrega Accept: application/json automaticamente. Retorna error si status >= 400
// incluyendo el status code y los primeros 200 bytes del body.
func HttpGetJSON(url string, headers map[string]string, timeout time.Duration) (map[string]any, error) {
client := &http.Client{Timeout: timeout}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("http_get_json: build request: %w", err)
}
req.Header.Set("Accept", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("http_get_json: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("http_get_json: read body: %w", err)
}
if resp.StatusCode >= 400 {
preview := body
if len(preview) > 200 {
preview = preview[:200]
}
shortURL := url
if len(shortURL) > 100 {
shortURL = shortURL[:100]
}
return nil, fmt.Errorf("http_get_json: HTTP %d at %q — %s", resp.StatusCode, shortURL, preview)
}
var result map[string]any
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("http_get_json: parse JSON: %w", err)
}
return result, nil
}