Pull Proclamations & Categories from API and store them in the database
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package netreq
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Makes a GET request to the specified URL and returns the JSON response
|
||||
// as a byte slice. If the request fails, it returns an error.
|
||||
func GetJSON[T any](url string) ([]T, error) {
|
||||
fmt.Println("Fetching:", url)
|
||||
res, err := http.Get(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if res.StatusCode > 299 {
|
||||
return nil, fmt.Errorf("status %d: %s", res.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// 1. Trim whitespace to find the first actual JSON character
|
||||
trimmed := bytes.TrimSpace(body)
|
||||
if len(trimmed) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var result []T
|
||||
|
||||
// 2. Determine if we are looking at an Array [ ] or an Object { }
|
||||
if trimmed[0] == '[' {
|
||||
// It's already an array, unmarshal directly
|
||||
err = json.Unmarshal(body, &result)
|
||||
} else {
|
||||
// It's a single object, unmarshal into a single instance and wrap it
|
||||
var single T
|
||||
err = json.Unmarshal(body, &single)
|
||||
result = []T{single}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse JSON: %w", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package netreq
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"rhemawavetech.com/rhemawave/internal/db"
|
||||
)
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
url := "http://localhost:5173/api/v1/proclamations"
|
||||
|
||||
// Explicitly tell GetJSON to return a slice of db.Proclamation
|
||||
proclamations, err := GetJSON[db.Proclamation](url)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("GetJSON failed: %v", err)
|
||||
}
|
||||
|
||||
if len(proclamations) == 0 {
|
||||
t.Fatal("GetJSON returned no records")
|
||||
}
|
||||
|
||||
// You can now inspect the actual struct fields instead of raw strings
|
||||
fmt.Printf("Fetched %d records. First ID: %s\n", len(proclamations), proclamations[0].ID)
|
||||
}
|
||||
Reference in New Issue
Block a user