From 891741efa642603a61f9b26d1c724e6e0c13476b Mon Sep 17 00:00:00 2001 From: larscom Date: Tue, 28 Nov 2023 19:43:10 +0100 Subject: [PATCH] add client --- Makefile | 4 +++ examples/time/main.go | 13 ++++++++++ httpclient.go | 60 +++++++++++++++++++++++++++++++++++++++++++ websocket.go | 1 + 4 files changed, 78 insertions(+) create mode 100644 examples/time/main.go create mode 100644 httpclient.go diff --git a/Makefile b/Makefile index fcd4377..5612295 100644 --- a/Makefile +++ b/Makefile @@ -10,6 +10,9 @@ trades: go run ./examples/trades/main.go account: go run ./examples/account/main.go + +time: + go run ./examples/time/main.go build: go build -o ./bin/candles ./examples/candles/main.go go build -o ./bin/book ./examples/book/main.go @@ -17,5 +20,6 @@ build: go build -o ./bin/ticker24h ./examples/ticker24h/main.go go build -o ./bin/trades ./examples/trades/main.go go build -o ./bin/account ./examples/account/main.go + go build -o ./bin/time ./examples/time/main.go test: go test -v ./.../ --race diff --git a/examples/time/main.go b/examples/time/main.go new file mode 100644 index 0000000..b1dd0f0 --- /dev/null +++ b/examples/time/main.go @@ -0,0 +1,13 @@ +package main + +import ( + "log" + + "github.com/larscom/go-bitvavo/v2" +) + +func main() { + client := bitvavo.NewHttpClient() + v, _ := client.GetTime() + log.Println("Time", v) +} diff --git a/httpclient.go b/httpclient.go new file mode 100644 index 0000000..b4ea2e1 --- /dev/null +++ b/httpclient.go @@ -0,0 +1,60 @@ +package bitvavo + +import ( + "fmt" + "io" + "net/http" + + "github.com/goccy/go-json" +) + +const ( + httpUrl = "https://api.bitvavo.com/v2" + maxRateLimit = 1000 +) + +type HttpClient interface { + GetTime() (int64, error) +} + +type httpClient struct { + rateLimit int64 +} + +func NewHttpClient() HttpClient { + return &httpClient{} +} + +func (h *httpClient) GetTime() (int64, error) { + r, err := httpGet[map[string]float64](fmt.Sprintf("%s/time", httpUrl)) + if err != nil { + return 0, err + } + + return int64(r["time"]), nil +} + +func httpGet[T any](url string) (T, error) { + var data T + + response, err := http.Get(url) + if err != nil { + return data, err + } + + if response.StatusCode != http.StatusOK { + return data, fmt.Errorf("did not get successfull response, code=%d", response.StatusCode) + } + + defer response.Body.Close() + bytes, err := io.ReadAll(response.Body) + if err != nil { + return data, err + } + + if err := json.Unmarshal(bytes, &data); err != nil { + return data, err + } + + return data, nil +} diff --git a/websocket.go b/websocket.go index 19a279e..afb366f 100644 --- a/websocket.go +++ b/websocket.go @@ -198,6 +198,7 @@ func (ws *webSocket) readLoop() { _, bytes, err := ws.conn.ReadMessage() if err != nil { defer ws.reconnect() + log.Logger().Error("Read failed", "error", err.Error()) return } ws.handleMessage(bytes)