|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file" |
| 12 | +) |
| 13 | + |
| 14 | +// DownloadAndStoreJSON is a generic function that: |
| 15 | +// - Downloads from the given URL if the local file is stale. |
| 16 | +// - Stores it in the given file path. |
| 17 | +// - Unmarshals the JSON bytes into a type T and returns a *T. |
| 18 | +// |
| 19 | +// T must be a Go type compatible with the JSON structure (e.g. a struct or slice). |
| 20 | +func DownloadAndStoreJSON[T any](url, filename string, cacheTTL time.Duration) (*T, error) { |
| 21 | + // Use your existing caching logic from "downloadAndStore" |
| 22 | + bytes, err := downloadAndStore(url, filename, cacheTTL) |
| 23 | + if err != nil { |
| 24 | + var zero T |
| 25 | + return &zero, err |
| 26 | + } |
| 27 | + |
| 28 | + var result T |
| 29 | + if err := json.Unmarshal(bytes, &result); err != nil { |
| 30 | + return &result, err |
| 31 | + } |
| 32 | + return &result, nil |
| 33 | +} |
| 34 | + |
| 35 | +// downloadAndStore retrieves data from the specified URL and caches it in the provided |
| 36 | +// filename for up to `dur`. If the file already exists and is newer than `dur`, it returns |
| 37 | +// the file's contents without making a network request. Otherwise, it fetches from the URL. |
| 38 | +// |
| 39 | +// If the server returns 404, the function writes an empty file to disk and returns a zero-length |
| 40 | +// byte slice. For other non-200 status codes, it returns an error. |
| 41 | +// |
| 42 | +// If the response is valid JSON, it is pretty-formatted before being saved; otherwise it is |
| 43 | +// saved as-is. The function returns the written file content as a byte slice. |
| 44 | +func downloadAndStore(url, filename string, dur time.Duration) ([]byte, error) { |
| 45 | + if file.FileExists(filename) { |
| 46 | + lastModDate, err := file.GetModTime(filename) |
| 47 | + if err != nil { |
| 48 | + return nil, err |
| 49 | + } |
| 50 | + if time.Since(lastModDate) < dur { |
| 51 | + data, err := os.ReadFile(filename) |
| 52 | + if err != nil { |
| 53 | + return nil, err |
| 54 | + } |
| 55 | + return data, nil |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + resp, err := http.Get(url) |
| 60 | + if err != nil { |
| 61 | + return nil, err |
| 62 | + } |
| 63 | + defer resp.Body.Close() |
| 64 | + |
| 65 | + if resp.StatusCode == http.StatusNotFound { |
| 66 | + // If the file doesn't exist remotely, store an empty file |
| 67 | + if err := os.WriteFile(filename, []byte{}, 0644); err != nil { |
| 68 | + return nil, err |
| 69 | + } |
| 70 | + // Optionally update its mod time |
| 71 | + _ = file.Touch(filename) |
| 72 | + return []byte{}, nil |
| 73 | + } else if resp.StatusCode != http.StatusOK { |
| 74 | + return nil, fmt.Errorf("received status %d %s for URL %s", |
| 75 | + resp.StatusCode, resp.Status, url) |
| 76 | + } |
| 77 | + |
| 78 | + rawData, err := io.ReadAll(resp.Body) |
| 79 | + if err != nil { |
| 80 | + return nil, err |
| 81 | + } |
| 82 | + |
| 83 | + var prettyData []byte |
| 84 | + if json.Valid(rawData) { |
| 85 | + var jsonData interface{} |
| 86 | + if err := json.Unmarshal(rawData, &jsonData); err != nil { |
| 87 | + return nil, err |
| 88 | + } |
| 89 | + prettyData, err = json.MarshalIndent(jsonData, "", " ") |
| 90 | + if err != nil { |
| 91 | + return nil, err |
| 92 | + } |
| 93 | + } else { |
| 94 | + prettyData = rawData |
| 95 | + } |
| 96 | + |
| 97 | + if err := os.WriteFile(filename, prettyData, 0644); err != nil { |
| 98 | + return nil, err |
| 99 | + } |
| 100 | + |
| 101 | + _ = file.Touch(filename) |
| 102 | + |
| 103 | + return prettyData, nil |
| 104 | +} |
0 commit comments