package bitgetapi import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "net/http" "net/url" "strings" "time" "github.com/c9s/requestgen" "github.com/pkg/errors" ) const defaultHTTPTimeout = time.Second * 15 const RestBaseURL = "https://api.bitget.com" const PublicWebSocketURL = "wss://ws.bitget.com/spot/v1/stream" const PrivateWebSocketURL = "wss://ws.bitget.com/spot/v1/stream" type RestClient struct { requestgen.BaseAPIClient key, secret, passphrase string } func NewClient() *RestClient { u, err := url.Parse(RestBaseURL) if err != nil { panic(err) } return &RestClient{ BaseAPIClient: requestgen.BaseAPIClient{ BaseURL: u, HttpClient: &http.Client{ Timeout: defaultHTTPTimeout, }, }, } } func (c *RestClient) Auth(key, secret, passphrase string) { c.key = key c.secret = secret c.passphrase = passphrase } // newAuthenticatedRequest creates new http request for authenticated routes. func (c *RestClient) NewAuthenticatedRequest(ctx context.Context, method, refURL string, params url.Values, payload interface{}) (*http.Request, error) { if len(c.key) == 0 { return nil, errors.New("empty api key") } if len(c.secret) == 0 { return nil, errors.New("empty api secret") } rel, err := url.Parse(refURL) if err != nil { return nil, err } if params != nil { rel.RawQuery = params.Encode() } pathURL := c.BaseURL.ResolveReference(rel) path := pathURL.Path if rel.RawQuery != "" { path += "?" + rel.RawQuery } // set location to UTC so that it outputs "2020-12-08T09:08:57.715Z" t := time.Now().In(time.UTC) timestamp := t.Format("2006-01-02T15:04:05.999Z07:00") body, err := castPayload(payload) if err != nil { return nil, err } signKey := timestamp + strings.ToUpper(method) + path + string(body) signature := sign(signKey, c.secret) req, err := http.NewRequestWithContext(ctx, method, pathURL.String(), bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Add("Content-Type", "application/json") req.Header.Add("Accept", "application/json") req.Header.Add("ACCESS-KEY", c.key) req.Header.Add("ACCESS-SIGN", signature) req.Header.Add("ACCESS-TIMESTAMP", timestamp) req.Header.Add("ACCESS-PASSPHRASE", c.passphrase) return req, nil } func sign(payload string, secret string) string { var sig = hmac.New(sha256.New, []byte(secret)) _, err := sig.Write([]byte(payload)) if err != nil { return "" } return base64.StdEncoding.EncodeToString(sig.Sum(nil)) } func castPayload(payload interface{}) ([]byte, error) { if payload == nil { return nil, nil } switch v := payload.(type) { case string: return []byte(v), nil case []byte: return v, nil } return json.Marshal(payload) }