28 lines
617 B
Go
28 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
|
||
|
|
}
|