bbgo_origin/pkg/datasource/coinmarketcap/v1/client.go

55 lines
1.1 KiB
Go
Raw Normal View History

2022-05-04 17:32:42 +00:00
package v1
import (
"context"
"net/http"
"net/url"
2022-05-11 17:49:59 +00:00
"time"
2022-05-04 17:32:42 +00:00
"github.com/c9s/requestgen"
)
const baseURL = "https://pro-api.coinmarketcap.com"
2022-05-11 17:49:59 +00:00
const defaultHTTPTimeout = time.Second * 15
2022-05-04 17:32:42 +00:00
type RestClient struct {
2022-05-11 17:49:59 +00:00
requestgen.BaseAPIClient
2022-05-04 17:32:42 +00:00
apiKey string
}
func New() *RestClient {
u, err := url.Parse(baseURL)
if err != nil {
panic(err)
}
return &RestClient{
2022-05-11 17:49:59 +00:00
BaseAPIClient: requestgen.BaseAPIClient{
BaseURL: u,
HttpClient: &http.Client{
Timeout: defaultHTTPTimeout,
},
},
2022-05-04 17:32:42 +00:00
}
}
func (c *RestClient) Auth(apiKey string) {
c.apiKey = apiKey
}
func (c *RestClient) NewAuthenticatedRequest(ctx context.Context, method, refURL string, params url.Values, payload interface{}) (*http.Request, error) {
req, err := c.NewRequest(ctx, method, refURL, params, payload)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
2022-05-11 17:49:59 +00:00
// Attach API Key to header. https://coinmarketcap.com/api/documentation/v1/#section/Authentication
2022-05-04 17:32:42 +00:00
req.Header.Add("X-CMC_PRO_API_KEY", c.apiKey)
return req, nil
}