|
1 | 1 | package chaintracker
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - "bytes" |
| 4 | + "context" |
5 | 5 | "encoding/json"
|
6 | 6 | "fmt"
|
7 | 7 | "net/http"
|
@@ -39,29 +39,41 @@ func NewWhatsOnChain(network Network, apiKey string) *WhatsOnChain {
|
39 | 39 | }
|
40 | 40 | }
|
41 | 41 |
|
42 |
| -func (w *WhatsOnChain) GetBlockHeader(height uint32) (*BlockHeader, error) { |
43 |
| - if req, err := http.NewRequest("GET", fmt.Sprintf("https://api.whatsonchain.com/v1/bsv/%s/block/%d/header", w.Network, height), bytes.NewBuffer([]byte{})); err != nil { |
| 42 | +// Assuming BlockHeader is defined elsewhere |
| 43 | +func (w *WhatsOnChain) GetBlockHeader(height uint32) (header *BlockHeader, err error) { |
| 44 | + url := fmt.Sprintf("https://api.whatsonchain.com/v1/bsv/%s/block/%d/header", w.Network, height) |
| 45 | + req, err := http.NewRequestWithContext(context.Background(), "GET", url, nil) |
| 46 | + if err != nil { |
44 | 47 | return nil, err
|
45 |
| - } else { |
46 |
| - req.Header.Set("Authorization", w.ApiKey) |
47 |
| - if resp, err := http.DefaultClient.Do(req); err != nil { |
48 |
| - return nil, err |
49 |
| - } else { |
50 |
| - defer resp.Body.Close() |
51 |
| - if resp.StatusCode == 404 { |
52 |
| - return nil, nil |
53 |
| - } |
54 |
| - if resp.StatusCode != 200 { |
55 |
| - return nil, fmt.Errorf("failed to verify merkleroot for height %d because of an error: %v", height, resp.Status) |
56 |
| - } |
57 |
| - header := &BlockHeader{} |
58 |
| - if err := json.NewDecoder(resp.Body).Decode(header); err != nil { |
59 |
| - return nil, err |
60 |
| - } |
| 48 | + } |
| 49 | + |
| 50 | + req.Header.Set("Authorization", w.ApiKey) |
61 | 51 |
|
62 |
| - return header, nil |
| 52 | + resp, err := http.DefaultClient.Do(req) |
| 53 | + if err != nil { |
| 54 | + return nil, err |
| 55 | + } |
| 56 | + // Ensure resp.Body.Close() is called and its error is handled |
| 57 | + defer func() { |
| 58 | + closeErr := resp.Body.Close() |
| 59 | + if closeErr != nil && err == nil { |
| 60 | + err = closeErr |
63 | 61 | }
|
| 62 | + }() |
| 63 | + |
| 64 | + if resp.StatusCode == http.StatusNotFound { |
| 65 | + return nil, nil |
64 | 66 | }
|
| 67 | + if resp.StatusCode != http.StatusOK { |
| 68 | + return nil, fmt.Errorf("failed to verify merkleroot for height %d: %v", height, resp.Status) |
| 69 | + } |
| 70 | + |
| 71 | + header = &BlockHeader{} |
| 72 | + if err := json.NewDecoder(resp.Body).Decode(header); err != nil { |
| 73 | + return nil, err |
| 74 | + } |
| 75 | + |
| 76 | + return header, nil |
65 | 77 | }
|
66 | 78 |
|
67 | 79 | func (w *WhatsOnChain) IsValidRootForHeight(root *chainhash.Hash, height uint32) (bool, error) {
|
|
0 commit comments