forked from sonirico/go-hyperliquid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
83 lines (70 loc) · 1.84 KB
/
client.go
File metadata and controls
83 lines (70 loc) · 1.84 KB
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
73
74
75
76
77
78
79
80
81
82
83
// Package hyperliquid provides a Go client library for the Hyperliquid exchange API.
// It includes support for both REST API and WebSocket connections, allowing users to
// access market data, manage orders, and handle user account operations.
package hyperliquid
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
const (
MainnetAPIURL = "https://api.hyperliquid.xyz"
TestnetAPIURL = "https://api.hyperliquid-testnet.xyz"
LocalAPIURL = "http://localhost:3001"
// httpErrorStatusCode is the minimum status code considered an error
httpErrorStatusCode = 400
)
type Client struct {
baseURL string
httpClient *http.Client
}
func NewClient(baseURL string) *Client {
if baseURL == "" {
baseURL = MainnetAPIURL
}
return &Client{
baseURL: baseURL,
httpClient: new(http.Client),
}
}
func (c *Client) post(path string, payload any) ([]byte, error) {
jsonData, err := json.Marshal(payload)
fmt.Println(string(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to marshal payload: %w", err)
}
url := c.baseURL + path
req, err := http.NewRequestWithContext(
context.Background(),
"POST",
url,
bytes.NewBuffer(jsonData),
)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body := make([]byte, 0)
if resp.Body != nil {
body, err = io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
}
if resp.StatusCode >= httpErrorStatusCode {
var apiErr APIError
if err := json.Unmarshal(body, &apiErr); err != nil {
return nil, fmt.Errorf("status %d: %s", resp.StatusCode, string(body))
}
return nil, apiErr
}
return body, nil
}