htmgo/htmgo-site/internal/httpjson/client.go
2024-09-26 21:15:04 -05:00

27 lines
617 B
Go

package httpjson
import (
"encoding/json"
"fmt"
"net/http"
)
// Get sends a GET request and decodes the response JSON into a generic type T
func Get[T any](url string) (*T, error) {
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to make GET request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("received non-OK status code: %d", resp.StatusCode)
}
var result T
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
return &result, nil
}