forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ledger_request.go
66 lines (57 loc) · 1.77 KB
/
ledger_request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package horizonclient
import (
"context"
"encoding/json"
"fmt"
"net/url"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/support/errors"
)
// BuildURL creates the endpoint to be queried based on the data in the LedgerRequest struct.
// If no data is set, it defaults to the build the URL for all ledgers
func (lr LedgerRequest) BuildURL() (endpoint string, err error) {
endpoint = "ledgers"
if lr.forSequence != 0 {
endpoint = fmt.Sprintf(
"%s/%d",
endpoint,
lr.forSequence,
)
} else {
queryParams := addQueryParams(cursor(lr.Cursor), limit(lr.Limit), lr.Order)
if queryParams != "" {
endpoint = fmt.Sprintf(
"%s?%s",
endpoint,
queryParams,
)
}
}
_, err = url.Parse(endpoint)
if err != nil {
err = errors.Wrap(err, "failed to parse endpoint")
}
return endpoint, err
}
// LedgerHandler is a function that is called when a new ledger is received
type LedgerHandler func(hProtocol.Ledger)
// StreamLedgers streams stellar ledgers. It can be used to stream all ledgers. Use context.WithCancel
// to stop streaming or context.Background() if you want to stream indefinitely.
// LedgerHandler is a user-supplied function that is executed for each streamed ledger received.
func (lr LedgerRequest) StreamLedgers(ctx context.Context, client *Client,
handler LedgerHandler) (err error) {
endpoint, err := lr.BuildURL()
if err != nil {
return errors.Wrap(err, "unable to build endpoint for ledger request")
}
url := fmt.Sprintf("%s%s", client.fixHorizonURL(), endpoint)
return client.stream(ctx, url, func(data []byte) error {
var ledger hProtocol.Ledger
err = json.Unmarshal(data, &ledger)
if err != nil {
return errors.Wrap(err, "error unmarshaling data for ledger request")
}
handler(ledger)
return nil
})
}