gocmc

package module
v0.0.0-...-dd3f439 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2026 License: MIT Imports: 12 Imported by: 0

README

gocmc

gocmc is a lightweight and idiomatic Go SDK for integrating with the CoinMarketCap API.

It is designed for simplicity, correctness, and ease of integration in production systems.

Go Version License

Features

  • Simple & Idiomatic API Clean, readable interfaces that follow Go best practices.

  • Context Support Full support for context.Context for cancellation and timeouts.

  • Zero External Dependencies Uses only the Go standard library.

  • Customizable Bring your own HTTP client, logger, or enable debug mode.

Installation

go get github.com/andyle182810/gocmc

Quick Start

client, err := gocmc.NewClient(
    "https://pro-api.coinmarketcap.com",
    apiKey,
    gocmc.WithDebug(true),
)
if err != nil {
    log.Fatal(err)
}

resp, err := client.GetLatestQuotes(
    context.Background(),
    &gocmc.GetLatestQuotesParams{
        Symbol:  []string{"BTC", "ETH"},
        Convert: []string{"USD"},
    },
)
if err != nil {
    log.Fatal(err)
}

fmt.Println("BTC price:", resp.Data["BTC"][0].Quote["USD"].Price)

Testing

Integration tests automatically skip when required credentials are missing.

Required environment variable:

CMC_API_KEY=your_api_key

Run tests:

go test ./...

Support

For bugs, questions, or feature requests:

License

gocmc is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const UserAgent = "coinmarketcap-go-sdk"

Variables

View Source
var (
	// Client initialization errors.
	ErrEmptyBaseURL = errors.New("base URL cannot be empty")
	ErrEmptyAPIKey  = errors.New("api key cannot be empty")

	// Request lifecycle errors.
	ErrNilRequest    = errors.New("request is nil")
	ErrRequestEncode = errors.New("failed to encode request body")

	// HTTP / transport errors.
	ErrHTTPFailure      = errors.New("http request failed")
	ErrUnexpectedStatus = errors.New("unexpected http status code")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Status struct {
		Timestamp    time.Time `json:"timestamp"`
		ErrorCode    int       `json:"error_code"`
		ErrorMessage string    `json:"error_message"`
		Elapsed      int       `json:"elapsed"`
		CreditCount  int       `json:"credit_count"`
	} `json:"status"`
}

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(baseURL, apiKey string, opts ...Option) (*Client, error)

func (*Client) GetLatestQuotes

func (c *Client) GetLatestQuotes(ctx context.Context, params *GetLatestQuotesParams) (*LatestQuotesResponse, error)

type CryptocurrencyQuote

type CryptocurrencyQuote struct {
	ID                            int                  `json:"id"`
	Name                          string               `json:"name"`
	Symbol                        string               `json:"symbol"`
	Slug                          string               `json:"slug"`
	NumMarketPairs                int                  `json:"num_market_pairs"`
	DateAdded                     time.Time            `json:"date_added"`
	Tags                          []Tag                `json:"tags"`
	MaxSupply                     *float64             `json:"max_supply"`
	CirculatingSupply             float64              `json:"circulating_supply"`
	TotalSupply                   float64              `json:"total_supply"`
	Platform                      *Platform            `json:"platform"`
	IsActive                      int                  `json:"is_active"`
	InfiniteSupply                bool                 `json:"infinite_supply"`
	MintedMarketCap               float64              `json:"minted_market_cap"`
	CMCRank                       int                  `json:"cmc_rank"`
	IsFiat                        int                  `json:"is_fiat"`
	SelfReportedCirculatingSupply *float64             `json:"self_reported_circulating_supply"`
	SelfReportedMarketCap         *float64             `json:"self_reported_market_cap"`
	TVLRatio                      *float64             `json:"tvl_ratio"`
	LastUpdated                   time.Time            `json:"last_updated"`
	Quote                         map[string]QuoteData `json:"quote"`
}

type GetLatestQuotesParams

type GetLatestQuotesParams struct {
	ID          []int
	Slug        []string
	Symbol      []string
	Convert     []string
	ConvertID   []int
	Aux         []string
	SkipInvalid *bool
}

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type LatestQuotesResponse

type LatestQuotesResponse struct {
	Status ResponseStatus                   `json:"status"`
	Data   map[string][]CryptocurrencyQuote `json:"-"`
}

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Error(msg string, args ...any)
	Debug(msg string, args ...any)
}

type Option

type Option func(*Client)

func WithDebug

func WithDebug(debug bool) Option

func WithHTTPClient

func WithHTTPClient(httpClient HTTPClient) Option

func WithLogger

func WithLogger(logger Logger) Option

type Platform

type Platform struct {
	ID           int    `json:"id"`
	Name         string `json:"name"`
	Symbol       string `json:"symbol"`
	Slug         string `json:"slug"`
	TokenAddress string `json:"token_address"`
}

type QuoteData

type QuoteData struct {
	Price                 float64   `json:"price"`
	Volume24h             float64   `json:"volume_24h"`
	VolumeChange24h       float64   `json:"volume_change_24h"`
	PercentChange1h       float64   `json:"percent_change_1h"`
	PercentChange24h      float64   `json:"percent_change_24h"`
	PercentChange7d       float64   `json:"percent_change_7d"`
	PercentChange30d      float64   `json:"percent_change_30d"`
	PercentChange60d      float64   `json:"percent_change_60d"`
	PercentChange90d      float64   `json:"percent_change_90d"`
	MarketCap             float64   `json:"market_cap"`
	MarketCapDominance    float64   `json:"market_cap_dominance"`
	FullyDilutedMarketCap float64   `json:"fully_diluted_market_cap"`
	TVL                   *float64  `json:"tvl"`
	LastUpdated           time.Time `json:"last_updated"`
}

type ResponseStatus

type ResponseStatus struct {
	Timestamp    time.Time `json:"timestamp"`
	ErrorCode    int       `json:"error_code"`
	ErrorMessage *string   `json:"error_message"`
	Elapsed      int       `json:"elapsed"`
	CreditCount  int       `json:"credit_count"`
	Notice       *string   `json:"notice"`
}

type Tag

type Tag struct {
	Slug     string `json:"slug"`
	Name     string `json:"name"`
	Category string `json:"category"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL