-
Notifications
You must be signed in to change notification settings - Fork 3
/
restful_provider.go
72 lines (64 loc) · 1.66 KB
/
restful_provider.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
67
68
69
70
71
72
package internal
import (
"fmt"
"sync"
"time"
"github.com/terra-money/oracle-feeder-go/internal/restful"
internal_types "github.com/terra-money/oracle-feeder-go/internal/types"
"github.com/terra-money/oracle-feeder-go/pkg/types"
"golang.org/x/exp/maps"
)
type RESTfulProvider struct {
priceBySymbol map[string]internal_types.PriceBySymbol
mu *sync.Mutex
}
func NewRESTfulProvider(exchange string, symbols []string, interval int, timeout int, stopCh <-chan struct{}) (*RESTfulProvider, error) {
client, err := restful.NewRESTfulClient(exchange, symbols)
if err != nil {
return nil, err
}
mu := sync.Mutex{}
provider := &RESTfulProvider{
priceBySymbol: make(map[string]internal_types.PriceBySymbol),
mu: &mu,
}
go func() {
ticker := time.NewTicker(time.Duration(interval) * time.Second)
prices, err := client.FetchAndParse(symbols, timeout)
if err == nil {
mu.Lock()
maps.Copy(provider.priceBySymbol, prices)
mu.Unlock()
}
for {
select {
case <-stopCh:
ticker.Stop()
return
case <-ticker.C:
prices, err := client.FetchAndParse(symbols, timeout)
if err == nil {
mu.Lock()
maps.Copy(provider.priceBySymbol, prices)
mu.Unlock()
}
}
}
}()
return provider, nil
}
func (p *RESTfulProvider) GetPrices() map[string]types.PriceByPair {
result := make(map[string]types.PriceByPair)
p.mu.Lock()
defer p.mu.Unlock()
for _, price := range p.priceBySymbol {
pair := fmt.Sprintf("%s/%s", price.Base, price.Quote)
result[pair] = types.PriceByPair{
Base: price.Base,
Quote: price.Quote,
Price: price.Price,
Timestamp: price.Timestamp,
}
}
return result
}