Documentation
¶
Overview ¶
Package cryptopanic provides a Go SDK for the CryptoPanic API (https://cryptopanic.com/developers/api/).
The SDK exposes a configurable, context-aware Client with typed methods for the publicly documented endpoints: Posts, Portfolio, and RSS feeds. All network-facing methods accept context.Context as their first parameter.
Index ¶
- Constants
- Variables
- func BoolPtr(b bool) *bool
- func IntPtr(i int) *int
- func StringPtr(s string) *string
- func TimePtr(t time.Time) *time.Time
- type APIError
- type Client
- func (c *Client) NewsRSS(ctx context.Context) (*RSSResponse, error)
- func (c *Client) Portfolio(ctx context.Context) (*PortfolioResponse, error)
- func (c *Client) Posts(ctx context.Context, query PostsQuery) (*PostsPage, error)
- func (c *Client) PostsRSS(ctx context.Context, query PostsQuery) (*RSSResponse, error)
- type Filter
- type Kind
- type Option
- type PanicPeriod
- type PanicSort
- type Plan
- type PortfolioResponse
- type Post
- type PostAuthor
- type PostContent
- type PostInstrument
- type PostSource
- type PostVotes
- type PostsPage
- type PostsQuery
- type RSSResponse
- type ResponseMetadata
- type RetryPolicy
- type Sleeper
Constants ¶
const DefaultBaseURL = "https://cryptopanic.com/api"
DefaultBaseURL is the default CryptoPanic API base URL. The {plan} segment is replaced at construction time based on the configured Plan option.
const DefaultMaxRetryAttempts = 0
DefaultMaxRetryAttempts is the default number of retry attempts (excluding the initial request) for transient failures. By default retries are disabled.
const DefaultRetryBaseDelay = 500 * time.Millisecond
DefaultRetryBaseDelay is the default initial backoff delay for retry attempts.
const DefaultRetryMaxDelay = 30 * time.Second
DefaultRetryMaxDelay is the maximum delay between retry attempts.
const DefaultTimeout = 30 * time.Second
DefaultTimeout is the default HTTP client timeout used unless overridden with WithTimeout.
const DefaultUserAgent = "cryptopanic-go/1.0.0"
DefaultUserAgent is the default User-Agent header value sent with every request.
Variables ¶
var ( // ErrMissingAuthToken is returned when no auth_token is provided. ErrMissingAuthToken = errors.New("cryptopanic: missing auth token — set CRYPTOPANIC_AUTH_TOKEN or pass a token to New") // ErrInvalidQuery is returned when local query validation fails. ErrInvalidQuery = errors.New("cryptopanic: invalid query parameters") ErrUnauthorized = errors.New("cryptopanic: unauthorized — check your auth token") // ErrForbidden is returned when the API responds with HTTP 403. ErrForbidden = errors.New("cryptopanic: forbidden — access or plan restriction") // ErrRateLimited is returned when the API responds with HTTP 429 // and all retry attempts have been exhausted. ErrRateLimited = errors.New("cryptopanic: rate limit exceeded") // ErrServerError is returned when the API responds with HTTP 500. ErrServerError = errors.New("cryptopanic: server error") )
Sentinel errors that can be checked with errors.Is against errors returned from methods. The underlying *APIError is always available via errors.As for accessing StatusCode, RawBody, etc.
Functions ¶
func BoolPtr ¶
BoolPtr returns a pointer to the provided bool value. Useful for populating optional pointer fields in PostsQuery.
Types ¶
type APIError ¶
type APIError struct {
// StatusCode is the HTTP status code returned by the API.
StatusCode int
// Message is a human-readable error message extracted from the
// response body or a generated fallback.
Message string
// RawBody contains a truncated, redacted copy of the raw response
// body for debugging purposes (max 512 bytes).
RawBody []byte
// RequestID is the value of the X-Request-ID response header, if
// the server provides one.
RequestID string
// Retried is the number of retry attempts made before this error
// was returned.
Retried int
}
APIError represents an error response returned by the CryptoPanic API. It is returned by every method when the API responds with a non-2xx HTTP status code. The error carries the status code, a safe response excerpt, and the request ID when available, but never includes the auth_token or a full sensitive request URL.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the entry point of the CryptoPanic Go SDK. It holds HTTP configuration and exposes methods for the publicly documented API endpoints. A Client is safe for concurrent use by multiple goroutines.
func New ¶
New creates a new CryptoPanic API client authenticated with the given auth_token. Behaviour can be customized via Option values such as WithPlan, WithBaseURL, WithHTTPClient, WithTimeout, WithRetryPolicy, and WithUserAgent.
The auth_token is sent as the auth_token query parameter on every request, as required by the CryptoPanic API. It is never placed in a URL path, user agent, error message, or log record.
func NewFromEnv ¶
NewFromEnv reads the auth_token from the CRYPTOPANIC_AUTH_TOKEN environment variable and returns a new CryptoPanic client. Additional Option values can be passed to override plan, timeouts, retries, etc.
func (*Client) NewsRSS ¶
func (c *Client) NewsRSS(ctx context.Context) (*RSSResponse, error)
NewsRSS retrieves the public CryptoPanic RSS news feed (GET /news/rss/). This is a public endpoint that does not require authentication, but the auth_token is still sent as documented. Returns raw RSS XML content.
Documentation: https://cryptopanic.com/developers/api/
func (*Client) Portfolio ¶
func (c *Client) Portfolio(ctx context.Context) (*PortfolioResponse, error)
Portfolio retrieves the authenticated user's portfolio from the CryptoPanic API (GET /portfolio/). This endpoint is available under Growth and Enterprise plans according to the public reference.
Because the public API reference does not specify a complete response schema, the response is returned as an opaque PortfolioResponse containing the raw decoded JSON. No domain model is fabricated.
Documentation: https://cryptopanic.com/developers/api/
func (*Client) Posts ¶
Posts retrieves a paginated list of news posts from the CryptoPanic API (GET /posts/). The query object controls filtering, currencies, regions, kind, pagination, and enterprise-gated parameters.
The auth_token is injected from the client configuration and never passed in the query object. Pagination URLs in the response are redacted: any auth_token parameter is removed before exposure.
Documentation: https://cryptopanic.com/developers/api/
func (*Client) PostsRSS ¶
func (c *Client) PostsRSS(ctx context.Context, query PostsQuery) (*RSSResponse, error)
PostsRSS retrieves the posts endpoint with format=rss, returning raw RSS XML content. The reference says format=rss returns 20 items regardless of plan. RSS content is preserved as XML and is not coerced into the JSON post page type.
Documentation: https://cryptopanic.com/developers/api/
type Filter ¶
type Filter string
Filter represents a known posts filter value. The CryptoPanic API documents filters such as rising, hot, bullish, bearish, important, saved, and lol. Custom string values are allowed for forward compatibility.
type Option ¶
type Option func(*Client)
Option configures a Client. Options are applied in the order they are passed to New.
func WithBaseURL ¶
WithBaseURL overrides the default CryptoPanic API base URL. This is primarily useful for testing against a mock server. The URL should not include the plan segment; an optional trailing slash is removed. The SDK appends /{plan}/v2/ automatically.
func WithHTTPClient ¶
WithHTTPClient sets a custom *http.Client used to perform requests. This allows callers to configure transport-level behaviour such as proxies, TLS settings, or custom RoundTrippers.
func WithPlan ¶
WithPlan sets the API plan segment used in the base URL. The default is PlanGrowth. Valid values are PlanDeveloper, PlanGrowth, and PlanEnterprise. Check the plans page at https://cryptopanic.com/developers/api/plans for commercial details.
func WithRetryPolicy ¶
func WithRetryPolicy(policy RetryPolicy) Option
WithRetryPolicy configures automatic retry behaviour for idempotent GET requests. Retries are applied for transient network failures, HTTP 429, and selected 5xx responses. The Retry-After header is honored when present. Exponential backoff with jitter is used otherwise. Retries are disabled by default.
func WithSleeper ¶
WithSleeper sets a custom Sleeper used for retry delays. This is primarily useful for testing to avoid real delays.
func WithTimeout ¶
WithTimeout sets the timeout applied to the underlying HTTP client for every request made by the Client.
func WithUserAgent ¶
WithUserAgent sets the User-Agent header value. The SDK name and version are included by default; this option overrides the entire value.
type PanicPeriod ¶
type PanicPeriod string
PanicPeriod represents a known panic period value.
const ( PanicPeriod1h PanicPeriod = "1h" PanicPeriod6h PanicPeriod = "6h" PanicPeriod24h PanicPeriod = "24h" )
PanicPeriod values identify the supported panic-score time windows.
type Plan ¶
type Plan string
Plan represents a CryptoPanic API plan segment used in the base URL.
const ( // PlanDeveloper is the developer plan segment. Note: the free // Developer API plan was discontinued. Check your account dashboard // and the plans page for current commercial details. PlanDeveloper Plan = "developer" // PlanGrowth is the growth plan segment. PlanGrowth Plan = "growth" // PlanEnterprise is the enterprise plan segment. PlanEnterprise Plan = "enterprise" )
type PortfolioResponse ¶
type PortfolioResponse struct {
// Raw contains the original decoded JSON from the portfolio
// endpoint response.
Raw json.RawMessage `json:"-"`
}
PortfolioResponse is an opaque/generic wrapper for the GET /portfolio/ endpoint. The public API reference does not specify a complete response schema, so the raw decoded JSON is retained instead of fabricating a domain model. Future schema expansion is backward compatible because callers access data through the Raw field.
type Post ¶
type Post struct {
// ID is the unique numeric post identifier.
ID int `json:"id"`
// Slug is the URL-friendly post slug.
Slug string `json:"slug"`
// Title is the post title.
Title string `json:"title"`
// Description is the post description/summary.
Description string `json:"description"`
// PublishedAt is the publication timestamp.
PublishedAt *time.Time `json:"published_at"`
// CreatedAt is the post creation timestamp.
CreatedAt *time.Time `json:"created_at"`
// Kind is the post kind (news, media).
Kind string `json:"kind"`
// Source is the source object.
Source *PostSource `json:"source"`
// OriginalURL is the original article URL.
OriginalURL string `json:"original_url"`
// URL is the CryptoPanic post URL.
URL string `json:"url"`
// Image is the post image URL (optional).
Image *string `json:"image"`
// Instruments is the list of tagged instruments.
Instruments []PostInstrument `json:"instruments"`
// Votes is the vote counts object.
Votes *PostVotes `json:"votes"`
// PanicScore is the overall panic score (optional/enterprise-gated).
PanicScore *int `json:"panic_score"`
// PanicScore1h is the 1-hour panic score (optional/enterprise-gated).
PanicScore1h *int `json:"panic_score_1h"`
// Author is the post author (optional).
Author *PostAuthor `json:"author"`
// Content is the post content (optional/enterprise-gated).
Content *PostContent `json:"content"`
}
Post represents a single news post in the CryptoPanic API response. Plan-gated or potentially omitted fields are nullable/optional. Additive fields sent by the service are not rejected.
type PostAuthor ¶
type PostAuthor struct {
// ID is the numeric author identifier.
ID int `json:"id"`
// Name is the display name of the author.
Name string `json:"name"`
// Slug is the URL-friendly author slug.
Slug string `json:"slug"`
// URL is the author's profile URL.
URL string `json:"url"`
// Avatar is the author's avatar URL.
Avatar string `json:"avatar"`
// Twitter is the author's Twitter handle.
Twitter string `json:"twitter"`
// Facebook is the author's Facebook profile.
Facebook string `json:"facebook"`
// LinkedIn is the author's LinkedIn profile.
LinkedIn string `json:"linkedin"`
}
PostAuthor represents the author of a post.
type PostContent ¶
type PostContent struct {
// Raw is the raw content text.
Raw string `json:"raw"`
}
PostContent represents the content object nested in a post. This field is enterprise-gated and may be null or absent.
type PostInstrument ¶
type PostInstrument struct {
// ID is the numeric instrument identifier.
ID int `json:"id"`
// Code is the instrument ticker code, e.g. BTC.
Code string `json:"code"`
// Slug is the URL-friendly instrument slug.
Slug string `json:"slug"`
// Title is the display name of the instrument.
Title string `json:"title"`
// Volume is the 24-hour trading volume.
Volume float64 `json:"volume"`
// Change is the 24-hour price change percentage.
Change float64 `json:"change"`
// Currency is the currency code.
Currency string `json:"currency"`
}
PostInstrument represents a currency instrument tagged on a post.
type PostSource ¶
type PostSource struct {
// Title is the display title of the source.
Title string `json:"title"`
// Region is the region code of the source.
Region string `json:"region"`
// Domain is the domain name of the source.
Domain string `json:"domain"`
// Path is the URL path of the source article.
Path string `json:"path"`
// CreatedAt is the source creation timestamp.
CreatedAt *time.Time `json:"created_at"`
}
PostSource represents the source object nested in a Post.
type PostVotes ¶
type PostVotes struct {
// Positive is the count of positive votes.
Positive int `json:"positive"`
// Negative is the count of negative votes.
Negative int `json:"negative"`
// Important is the count of important votes.
Important int `json:"important"`
// Liked is the count of liked votes.
Liked int `json:"liked"`
// Disliked is the count of disliked votes.
Disliked int `json:"disliked"`
// Lol is the count of lol votes.
Lol int `json:"lol"`
// Toxic is the count of toxic votes.
Toxic int `json:"toxic"`
// Comments is the count of comments.
Comments int `json:"comments"`
// Saved is the count of saved votes.
Saved int `json:"saved"`
}
PostVotes represents the vote counts on a post.
type PostsPage ¶
type PostsPage struct {
// Results is the list of posts on the current page.
Results []Post `json:"results"`
// Next is the redacted URL for the next page, or empty if there
// is no next page.
Next string `json:"-"`
// Previous is the redacted URL for the previous page, or empty if
// there is no previous page.
Previous string `json:"-"`
// HasNext indicates whether a next page exists.
HasNext bool `json:"-"`
// HasPrevious indicates whether a previous page exists.
HasPrevious bool `json:"-"`
// NextPage extracts the page number from the next URL, if available.
NextPage *int `json:"-"`
// PreviousPage extracts the page number from the previous URL, if available.
PreviousPage *int `json:"-"`
}
PostsPage represents the paginated envelope returned by GET /posts/. The Next and Previous fields are redacted: any auth_token query parameter is removed before exposure.
type PostsQuery ¶
type PostsQuery struct {
// Public is an optional boolean for public mode.
Public *bool
// Currencies is an optional list encoded as a comma-separated
// set, e.g. BTC,ETH.
Currencies []string
// Regions is an optional region code or supported region
// collection. Default is "en".
Regions string
// Filter is an optional known filter. Custom values are allowed.
Filter Filter
// Kind is an optional known kind. Default is "all".
Kind Kind
// Following is an optional boolean for strictly private usage.
Following *bool
// LastPull is an optional RFC 3339 / ISO-8601 timestamp.
// Enterprise-gated in the reference.
LastPull *time.Time
// PanicPeriod is an optional panic period (1h, 6h, 24h).
// Enterprise-gated in the reference.
PanicPeriod PanicPeriod
// PanicSort is an optional sort direction (asc, desc). Rejected
// locally when PanicPeriod is absent. Enterprise-gated.
PanicSort PanicSort
// Size is an optional integer in the inclusive range 1–50.
// Enterprise-gated in the reference.
Size *int
// Page is an optional integer in the inclusive range 1–50.
// Default is 1.
Page *int
// WithContent is an optional boolean.
// Enterprise-gated in the reference.
WithContent *bool
// Search is an optional non-empty search string.
// Enterprise-gated in the reference.
Search string
}
PostsQuery holds the query parameters for the GET /posts/ endpoint. Authentication is configured on the Client, not in the query object. Only clear client-side syntax and cross-field rules are validated; the CryptoPanic server remains the authority for plan eligibility and evolving allowed values.
func (*PostsQuery) ToValues ¶
func (q *PostsQuery) ToValues() url.Values
ToValues converts the PostsQuery into url.Values suitable for use with the HTTP transport. Zero/empty values are omitted.
func (*PostsQuery) Validate ¶
func (q *PostsQuery) Validate() error
Validate checks local client-side syntax and cross-field rules. The CryptoPanic server remains the authority for plan eligibility.
type RSSResponse ¶
type RSSResponse struct {
// Body contains the raw RSS XML content.
Body string
}
RSSResponse represents a raw RSS feed response. The body is preserved as raw text/XML rather than being coerced into the JSON post page type.
type ResponseMetadata ¶
type ResponseMetadata struct {
// StatusCode is the HTTP status code.
StatusCode int
// RequestID is the value of the X-Request-ID header, if present.
RequestID string
// Duration is the time taken for the HTTP round-trip.
Duration time.Duration
}
ResponseMetadata holds non-body information from an HTTP response.
type RetryPolicy ¶
type RetryPolicy struct {
// MaxAttempts is the maximum number of retry attempts (excluding
// the initial request). Set to 0 to disable retries.
MaxAttempts int
// BaseDelay is the initial backoff delay.
BaseDelay time.Duration
// MaxDelay caps the delay between retries.
MaxDelay time.Duration
}
RetryPolicy controls the retry behaviour for idempotent GET requests. Retries are disabled by default (MaxAttempts = 0).
