Documentation
¶
Overview ¶
Package webshare provides the official Go SDK for the Webshare proxy API (https://apidocs.webshare.io).
Construct a client with NewClient and call methods on its resource services:
client, err := webshare.NewClient(webshare.WithAPIKey("..."))
if err != nil {
log.Fatal(err)
}
page, err := client.Proxies.List(ctx, webshare.ProxyListParams{Mode: webshare.ModeDirect})
When no credential option is given, the client reads the WEBSHARE_API_KEY environment variable.
Index ¶
- Constants
- func Bool(v bool) *bool
- func Float64(v float64) *float64
- func Int(v int) *int
- func Int64(v int64) *int64
- func ProxyURL(params ProxyURLParams) (string, error)
- func Ptr[T any](v T) *T
- func String(v string) *string
- func Time(v time.Time) *time.Time
- type ASNInfo
- type ASNNumber
- type AbuseReport
- type AbuseReportListParams
- type AggregateStats
- type AllocateUnallocatedCountriesParams
- type AppealState
- type AssetInfo
- type AuthenticationMethod
- type BillingInfo
- type BillingInfoUpdateParams
- type BillingService
- type CheckoutBehavior
- type Client
- type ConnectionMode
- type CouponCode
- type CouponDiscount
- type CouponPromoType
- type CrossOriginError
- type CustomizationFeature
- type CustomizationTerm
- type DownloadToken
- type DownloadTokenScope
- type DownloadTokensService
- type EarnoutStatus
- type Error
- type FeaturePrice
- type File
- type IDVerification
- type IDVerificationService
- type IDVerificationState
- type IPAuthorization
- type IPAuthorizationCreateParams
- type IPAuthorizationGetParams
- type IPAuthorizationListParams
- type IPAuthorizationsService
- func (s *IPAuthorizationsService) Create(ctx context.Context, params IPAuthorizationCreateParams, opts ...RequestOption) (*IPAuthorization, error)
- func (s *IPAuthorizationsService) Delete(ctx context.Context, id int, params IPAuthorizationGetParams, ...) error
- func (s *IPAuthorizationsService) Get(ctx context.Context, id int, params IPAuthorizationGetParams, ...) (*IPAuthorization, error)
- func (s *IPAuthorizationsService) List(ctx context.Context, params IPAuthorizationListParams, opts ...RequestOption) (*Page[IPAuthorization], error)
- func (s *IPAuthorizationsService) ListAll(ctx context.Context, params IPAuthorizationListParams, opts ...RequestOption) iter.Seq2[IPAuthorization, error]
- func (s *IPAuthorizationsService) WhatsMyIP(ctx context.Context, opts ...RequestOption) (*WhatsMyIPResult, error)
- type InvoicesService
- type Notification
- type NotificationListParams
- type NotificationsService
- func (s *NotificationsService) Dismiss(ctx context.Context, id int, opts ...RequestOption) (*Notification, error)
- func (s *NotificationsService) Get(ctx context.Context, id int, opts ...RequestOption) (*Notification, error)
- func (s *NotificationsService) List(ctx context.Context, params NotificationListParams, opts ...RequestOption) (*Page[Notification], error)
- func (s *NotificationsService) ListAll(ctx context.Context, params NotificationListParams, opts ...RequestOption) iter.Seq2[Notification, error]
- func (s *NotificationsService) Restore(ctx context.Context, id int, opts ...RequestOption) (*Notification, error)
- type Nullable
- type Page
- type PaymentMethod
- type PaymentMethodListParams
- type PaymentMethodType
- type PaymentMethodsService
- func (s *PaymentMethodsService) Get(ctx context.Context, id int, opts ...RequestOption) (*PaymentMethod, error)
- func (s *PaymentMethodsService) List(ctx context.Context, params PaymentMethodListParams, opts ...RequestOption) (*Page[PaymentMethod], error)
- func (s *PaymentMethodsService) ListAll(ctx context.Context, params PaymentMethodListParams, opts ...RequestOption) iter.Seq2[PaymentMethod, error]
- type PendingPayment
- type PendingPaymentListParams
- type PendingPaymentStatus
- type PendingPaymentsService
- func (s *PendingPaymentsService) Get(ctx context.Context, id int, opts ...RequestOption) (*PendingPayment, error)
- func (s *PendingPaymentsService) List(ctx context.Context, params PendingPaymentListParams, opts ...RequestOption) (*Page[PendingPayment], error)
- func (s *PendingPaymentsService) ListAll(ctx context.Context, params PendingPaymentListParams, opts ...RequestOption) iter.Seq2[PendingPayment, error]
- type Plan
- type PlanBundleAddon
- type PlanBundleInfo
- type PlanCancelResult
- type PlanConfiguration
- type PlanListParams
- type PlanStatus
- type PlanUpdateParams
- type PlansService
- func (s *PlansService) Cancel(ctx context.Context, id int, opts ...RequestOption) (*PlanCancelResult, error)
- func (s *PlansService) Get(ctx context.Context, id int, opts ...RequestOption) (*Plan, error)
- func (s *PlansService) List(ctx context.Context, params PlanListParams, opts ...RequestOption) (*Page[Plan], error)
- func (s *PlansService) ListAll(ctx context.Context, params PlanListParams, opts ...RequestOption) iter.Seq2[Plan, error]
- func (s *PlansService) Update(ctx context.Context, id int, params PlanUpdateParams, opts ...RequestOption) (*Plan, error)
- type PricingTier
- type Profile
- type ProfilePreferences
- type ProfilePreferencesUpdateParams
- type ProfileService
- func (s *ProfileService) Get(ctx context.Context, opts ...RequestOption) (*Profile, error)
- func (s *ProfileService) GetPreferences(ctx context.Context, opts ...RequestOption) (*ProfilePreferences, error)
- func (s *ProfileService) Update(ctx context.Context, params ProfileUpdateParams, opts ...RequestOption) (*Profile, error)
- func (s *ProfileService) UpdatePreferences(ctx context.Context, params ProfilePreferencesUpdateParams, ...) (*ProfilePreferences, error)
- type ProfileUpdateParams
- type ProxiesService
- func (s *ProxiesService) Download(ctx context.Context, params ProxyDownloadParams, opts ...RequestOption) (string, error)
- func (s *ProxiesService) DownloadURL(params ProxyDownloadParams) (string, error)
- func (s *ProxiesService) List(ctx context.Context, params ProxyListParams, opts ...RequestOption) (*Page[Proxy], error)
- func (s *ProxiesService) ListAll(ctx context.Context, params ProxyListParams, opts ...RequestOption) iter.Seq2[Proxy, error]
- func (s *ProxiesService) Refresh(ctx context.Context, params ProxyRefreshParams, opts ...RequestOption) error
- type Proxy
- type ProxyActivity
- type ProxyActivityDownloadParams
- type ProxyActivityListParams
- type ProxyActivityService
- func (s *ProxyActivityService) Download(ctx context.Context, params ProxyActivityDownloadParams, opts ...RequestOption) (string, error)
- func (s *ProxyActivityService) List(ctx context.Context, params ProxyActivityListParams, opts ...RequestOption) (*Page[ProxyActivity], error)
- func (s *ProxyActivityService) ListAll(ctx context.Context, params ProxyActivityListParams, opts ...RequestOption) iter.Seq2[ProxyActivity, error]
- type ProxyConfig
- type ProxyConfigService
- func (s *ProxyConfigService) AllocateUnallocatedCountries(ctx context.Context, params AllocateUnallocatedCountriesParams, ...) (*ProxyConfig, error)
- func (s *ProxyConfigService) Get(ctx context.Context, planID int, opts ...RequestOption) (*ProxyConfigV3, error)
- func (s *ProxyConfigService) GetStats(ctx context.Context, planID int, opts ...RequestOption) (*ProxyListStats, error)
- func (s *ProxyConfigService) GetStatus(ctx context.Context, planID int, opts ...RequestOption) (*ProxyListStatus, error)
- func (s *ProxyConfigService) Update(ctx context.Context, params ProxyConfigUpdateParams, opts ...RequestOption) (*ProxyConfig, error)
- type ProxyConfigState
- type ProxyConfigUpdateParams
- type ProxyConfigV3
- type ProxyDownloadParams
- type ProxyListParams
- type ProxyListStats
- type ProxyListStatus
- type ProxyRefreshParams
- type ProxyReplacement
- type ProxyReplacementCreateParams
- type ProxyReplacementGetParams
- type ProxyReplacementListParams
- type ProxyReplacementsService
- func (s *ProxyReplacementsService) Create(ctx context.Context, params ProxyReplacementCreateParams, ...) (*ProxyReplacement, error)
- func (s *ProxyReplacementsService) Get(ctx context.Context, id int, params ProxyReplacementGetParams, ...) (*ProxyReplacement, error)
- func (s *ProxyReplacementsService) List(ctx context.Context, params ProxyReplacementListParams, opts ...RequestOption) (*Page[ProxyReplacement], error)
- func (s *ProxyReplacementsService) ListAll(ctx context.Context, params ProxyReplacementListParams, opts ...RequestOption) iter.Seq2[ProxyReplacement, error]
- type ProxyStat
- type ProxyState
- type ProxySubtype
- type ProxyType
- type ProxyURLParams
- type ReferralChannel
- type ReferralCodeInfo
- type ReferralConfig
- type ReferralConfigUpdateParams
- type ReferralCredit
- type ReferralCreditListParams
- type ReferralCreditStatus
- type ReferralEarnout
- type ReferralEarnoutListParams
- type ReferralMode
- type ReferralService
- func (s *ReferralService) ApplyCouponCode(ctx context.Context, code string, opts ...RequestOption) (*CouponCode, error)
- func (s *ReferralService) GetCodeInfo(ctx context.Context, referralCode string, opts ...RequestOption) (*ReferralCodeInfo, error)
- func (s *ReferralService) GetConfig(ctx context.Context, opts ...RequestOption) (*ReferralConfig, error)
- func (s *ReferralService) GetCouponCode(ctx context.Context, opts ...RequestOption) (*CouponCode, error)
- func (s *ReferralService) GetCredit(ctx context.Context, id int, opts ...RequestOption) (*ReferralCredit, error)
- func (s *ReferralService) GetEarnout(ctx context.Context, id int, opts ...RequestOption) (*ReferralEarnout, error)
- func (s *ReferralService) ListAllCredits(ctx context.Context, params ReferralCreditListParams, opts ...RequestOption) iter.Seq2[ReferralCredit, error]
- func (s *ReferralService) ListAllEarnouts(ctx context.Context, params ReferralEarnoutListParams, opts ...RequestOption) iter.Seq2[ReferralEarnout, error]
- func (s *ReferralService) ListChannels(ctx context.Context, opts ...RequestOption) ([]ReferralChannel, error)
- func (s *ReferralService) ListCredits(ctx context.Context, params ReferralCreditListParams, opts ...RequestOption) (*Page[ReferralCredit], error)
- func (s *ReferralService) ListEarnouts(ctx context.Context, params ReferralEarnoutListParams, opts ...RequestOption) (*Page[ReferralEarnout], error)
- func (s *ReferralService) RemoveCouponCode(ctx context.Context, opts ...RequestOption) error
- func (s *ReferralService) UpdateConfig(ctx context.Context, params ReferralConfigUpdateParams, opts ...RequestOption) (*ReferralConfig, error)
- type ReplacedProxiesService
- func (s *ReplacedProxiesService) Download(ctx context.Context, params ReplacedProxyDownloadParams, opts ...RequestOption) (string, error)
- func (s *ReplacedProxiesService) List(ctx context.Context, params ReplacedProxyListParams, opts ...RequestOption) (*Page[ReplacedProxy], error)
- func (s *ReplacedProxiesService) ListAll(ctx context.Context, params ReplacedProxyListParams, opts ...RequestOption) iter.Seq2[ReplacedProxy, error]
- type ReplacedProxy
- type ReplacedProxyDownloadParams
- type ReplacedProxyListParams
- type ReplacementReason
- type ReplacementState
- type ReplacementTarget
- type ReplacementTargetType
- type RequestError
- type RequestOption
- func WithAPIKey(key string) RequestOption
- func WithBaseURL(rawURL string) RequestOption
- func WithFederatedUser(id int64) RequestOption
- func WithHTTPClient(hc *http.Client) RequestOption
- func WithHeader(key, value string) RequestOption
- func WithMaxRetries(n int) RequestOption
- func WithRetryNonIdempotent() RequestOption
- func WithSource(source string) RequestOption
- func WithSubuser(id int64) RequestOption
- func WithTimeout(d time.Duration) RequestOption
- func WithTokenSource(ts TokenSource) RequestOption
- func WithUnauthenticated() RequestOption
- type ResponseDecodeError
- type SiteCheck
- type StatErrorReason
- type StatsListParams
- type StatsService
- type SubmitAnswerParams
- type SubmitEvidenceParams
- type SubmitSecurityCodeParams
- type Subscription
- type SubscriptionCustomization
- type SubscriptionCustomizeParams
- type SubscriptionPricing
- type SubscriptionPricingParams
- type SubscriptionPromoType
- type SubscriptionService
- func (s *SubscriptionService) CancelAutoRenewal(ctx context.Context, opts ...RequestOption) (*Subscription, error)
- func (s *SubscriptionService) Customize(ctx context.Context, params SubscriptionCustomizeParams, opts ...RequestOption) (*SubscriptionCustomization, error)
- func (s *SubscriptionService) EnableAutoRenewal(ctx context.Context, opts ...RequestOption) (*Subscription, error)
- func (s *SubscriptionService) Get(ctx context.Context, opts ...RequestOption) (*Subscription, error)
- func (s *SubscriptionService) GetAvailableAssets(ctx context.Context, opts ...RequestOption) (map[string]map[string]AssetInfo, error)
- func (s *SubscriptionService) Pricing(ctx context.Context, params SubscriptionPricingParams, opts ...RequestOption) (*SubscriptionPricing, error)
- type SubscriptionTerm
- type Subuser
- type SubuserCreateParams
- type SubuserGetParams
- type SubuserListParams
- type SubuserUpdateParams
- type SubusersService
- func (s *SubusersService) Create(ctx context.Context, params SubuserCreateParams, opts ...RequestOption) (*Subuser, error)
- func (s *SubusersService) Delete(ctx context.Context, id int, params SubuserGetParams, opts ...RequestOption) error
- func (s *SubusersService) Get(ctx context.Context, id int, params SubuserGetParams, opts ...RequestOption) (*Subuser, error)
- func (s *SubusersService) List(ctx context.Context, params SubuserListParams, opts ...RequestOption) (*Page[Subuser], error)
- func (s *SubusersService) ListAll(ctx context.Context, params SubuserListParams, opts ...RequestOption) iter.Seq2[Subuser, error]
- func (s *SubusersService) RefreshProxyList(ctx context.Context, id int, opts ...RequestOption) (*Subuser, error)
- func (s *SubusersService) Update(ctx context.Context, id int, params SubuserUpdateParams, opts ...RequestOption) (*Subuser, error)
- type Suspension
- type TaxEntry
- type TaxRateDetails
- type Token
- type TokenSource
- type Transaction
- type TransactionListParams
- type TransactionStatus
- type TransactionsService
- func (s *TransactionsService) Get(ctx context.Context, id int, opts ...RequestOption) (*Transaction, error)
- func (s *TransactionsService) List(ctx context.Context, params TransactionListParams, opts ...RequestOption) (*Page[Transaction], error)
- func (s *TransactionsService) ListAll(ctx context.Context, params TransactionListParams, opts ...RequestOption) iter.Seq2[Transaction, error]
- type VerificationAbuseReportsService
- func (s *VerificationAbuseReportsService) List(ctx context.Context, params AbuseReportListParams, opts ...RequestOption) (*Page[AbuseReport], error)
- func (s *VerificationAbuseReportsService) ListAll(ctx context.Context, params AbuseReportListParams, opts ...RequestOption) iter.Seq2[AbuseReport, error]
- type VerificationAnswer
- type VerificationAppeal
- type VerificationAppealCreateParams
- type VerificationAppealListParams
- type VerificationAppealsService
- func (s *VerificationAppealsService) Create(ctx context.Context, params VerificationAppealCreateParams, ...) (*VerificationAppeal, error)
- func (s *VerificationAppealsService) List(ctx context.Context, params VerificationAppealListParams, ...) (*Page[VerificationAppeal], error)
- func (s *VerificationAppealsService) ListAll(ctx context.Context, params VerificationAppealListParams, ...) iter.Seq2[VerificationAppeal, error]
- type VerificationCategory
- type VerificationEvidence
- type VerificationFile
- type VerificationFlow
- type VerificationFlowListParams
- type VerificationFlowState
- type VerificationFlowType
- type VerificationFlowsService
- func (s *VerificationFlowsService) Get(ctx context.Context, id int, opts ...RequestOption) (*VerificationFlow, error)
- func (s *VerificationFlowsService) List(ctx context.Context, params VerificationFlowListParams, opts ...RequestOption) (*Page[VerificationFlow], error)
- func (s *VerificationFlowsService) ListAll(ctx context.Context, params VerificationFlowListParams, opts ...RequestOption) iter.Seq2[VerificationFlow, error]
- func (s *VerificationFlowsService) SubmitEvidence(ctx context.Context, id int, params SubmitEvidenceParams, ...) (*VerificationFlow, error)
- func (s *VerificationFlowsService) SubmitSecurityCode(ctx context.Context, id int, params SubmitSecurityCodeParams, ...) (*VerificationFlow, error)
- type VerificationLimits
- type VerificationQuestion
- type VerificationQuestionListParams
- type VerificationQuestionsService
- func (s *VerificationQuestionsService) List(ctx context.Context, params VerificationQuestionListParams, ...) (*Page[VerificationQuestion], error)
- func (s *VerificationQuestionsService) ListAll(ctx context.Context, params VerificationQuestionListParams, ...) iter.Seq2[VerificationQuestion, error]
- func (s *VerificationQuestionsService) SubmitAnswer(ctx context.Context, questionID int, params SubmitAnswerParams, ...) (*VerificationAnswer, error)
- type VerificationService
- func (s *VerificationService) GetCategories(ctx context.Context, opts ...RequestOption) (map[string]VerificationCategory, error)
- func (s *VerificationService) GetLimits(ctx context.Context, opts ...RequestOption) (*VerificationLimits, error)
- func (s *VerificationService) GetSuspension(ctx context.Context, opts ...RequestOption) (*Suspension, error)
- func (s *VerificationService) GetThresholds(ctx context.Context, opts ...RequestOption) (map[string]VerificationThreshold, error)
- type VerificationThreshold
- type WhatsMyIPResult
Examples ¶
Constants ¶
const BackboneHost = "p.webshare.io"
BackboneHost is the host used for backbone-mode proxy connections.
const DefaultAuthScheme = "Token"
DefaultAuthScheme is the Authorization header scheme used when a Token does not specify one. All Webshare API keys and login tokens use this scheme.
const DefaultBaseURL = "https://proxy.webshare.io"
DefaultBaseURL is the default API base URL. It is the bare host: every operation path carries its full /api/vN/... prefix.
const Version = "0.1.0"
Version is the SDK version, reported in the User-Agent header.
Variables ¶
This section is empty.
Functions ¶
func ProxyURL ¶
func ProxyURL(params ProxyURLParams) (string, error)
ProxyURL builds a proxy connection URL. In direct mode it produces "http://user:pass@address:port"; in backbone mode it targets p.webshare.io and encodes country, city and session parameters into the username using the {username}[-{cc}...][-city_{name}][-{session}|-rotate] grammar. When no credentials are given, an IP-authorization URL without user info is built.
Example ¶
package main
import (
"fmt"
"log"
webshare "github.com/webshare-proxy/webshare-go"
)
func main() {
proxyURL, err := webshare.ProxyURL(webshare.ProxyURLParams{
Mode: webshare.ModeBackbone,
Username: "myuser",
Password: "mypassword",
CountryCodes: []string{"US"},
SessionID: "1234",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(proxyURL)
}
Output: http://myuser-us-1234:mypassword@p.webshare.io:80
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns a pointer to v, for use in optional request fields. The typed helpers below cover the common cases; Ptr covers everything else.
Types ¶
type ASNInfo ¶
type ASNInfo struct {
// Name is the ASN name.
Name string
// Count is the number of proxies in the ASN.
Count int
}
ASNInfo describes an ASN entry in the proxy configuration maps. On the wire it is a heterogeneous two-element array: ["ASN NAME", 105].
func (ASNInfo) MarshalJSON ¶
MarshalJSON implements json.Marshaler, producing the wire tuple form.
func (*ASNInfo) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler for the wire tuple form.
type ASNNumber ¶
type ASNNumber string
ASNNumber is an ASN number that tolerates both string and numeric wire forms (the docs type it as string while some examples use integers). It always serializes as a string.
func (*ASNNumber) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type AbuseReport ¶
type AbuseReport struct {
// ID is the unique identifier of the abuse report.
ID int `json:"id"`
// Content is the content of the abuse report.
Content string `json:"content"`
// Flow is the related account verification flow ID. May be nil.
Flow *int `json:"flow"`
// CreatedAt is when the report was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the report was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
AbuseReport is an abuse report raised against the account.
type AbuseReportListParams ¶
type AbuseReportListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
AbuseReportListParams are the parameters for VerificationAbuseReportsService.List.
type AggregateStats ¶
type AggregateStats struct {
// BandwidthProjected is the projected bandwidth for the period in bytes.
BandwidthProjected int64 `json:"bandwidth_projected"`
// BandwidthTotal is the total bandwidth use in bytes.
BandwidthTotal int64 `json:"bandwidth_total"`
// BandwidthAverage is the average bandwidth in bytes per request.
BandwidthAverage int64 `json:"bandwidth_average"`
// RequestsTotal is the number of proxy requests made.
RequestsTotal int64 `json:"requests_total"`
// RequestsSuccessful is the number of successful proxy requests.
RequestsSuccessful int64 `json:"requests_successful"`
// RequestsFailed is the number of failed proxy requests.
RequestsFailed int64 `json:"requests_failed"`
// ErrorReasons lists the error reasons.
ErrorReasons []StatErrorReason `json:"error_reasons"`
// CountriesUsed maps country code to request count.
CountriesUsed map[string]int64 `json:"countries_used"`
// NumberOfProxiesUsed is the estimated number of unique proxy addresses
// used.
NumberOfProxiesUsed int `json:"number_of_proxies_used"`
// ProtocolsUsed maps proxy protocol (http, socks) to request count.
ProtocolsUsed map[string]int64 `json:"protocols_used"`
// AverageConcurrency is the estimated average number of concurrent
// proxy requests.
AverageConcurrency *float64 `json:"average_concurrency"`
// AverageRPS is the estimated average proxy requests per second.
AverageRPS *float64 `json:"average_rps"`
// LastRequestSentAt is when the last proxy request was sent.
LastRequestSentAt *time.Time `json:"last_request_sent_at"`
}
AggregateStats is the aggregated proxy usage for a period. It is also the shape of a sub-user's aggregate_stats field.
type AllocateUnallocatedCountriesParams ¶
type AllocateUnallocatedCountriesParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int `json:"-"`
// NewCountries maps upper-case country code to the number of proxies to
// allocate. The total must exactly match the number of unallocated
// proxies. Required.
NewCountries map[string]int `json:"new_countries"`
}
AllocateUnallocatedCountriesParams are the parameters for ProxyConfigService.AllocateUnallocatedCountries.
type AppealState ¶
type AppealState string
AppealState is the state of a suspension appeal.
const ( // AppealApproved means the appeal was approved. AppealApproved AppealState = "approved" // AppealRejected means the appeal was rejected. AppealRejected AppealState = "rejected" // AppealSubmitted means the appeal is awaiting review. AppealSubmitted AppealState = "submitted" )
Appeal states.
type AssetInfo ¶
type AssetInfo struct {
// TotalSubnets is the number of subnets available under the category.
TotalSubnets int `json:"total_subnets"`
// AvailableCountries maps country code to the number of proxies
// available in that country.
AvailableCountries map[string]int `json:"available_countries"`
}
AssetInfo describes the assets available for one proxy category and subtype.
type AuthenticationMethod ¶
type AuthenticationMethod string
AuthenticationMethod selects how downloaded proxies are authenticated.
const ( // AuthMethodUsername authenticates with username and password. AuthMethodUsername AuthenticationMethod = "username" // AuthMethodSourceIP authenticates by source IP address. AuthMethodSourceIP AuthenticationMethod = "sourceip" )
Authentication methods for proxy list downloads.
type BillingInfo ¶
type BillingInfo struct {
// ID is the unique identifier of the billing information instance.
ID int `json:"id"`
// Name appears on invoices; it can be a company name.
Name string `json:"name"`
// Address appears on invoices; it can be a corporate address.
Address string `json:"address"`
// BillingEmail appears on invoices.
BillingEmail string `json:"billing_email"`
// CreatedAt is when the account was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
BillingInfo is the billing information singleton of the account.
type BillingInfoUpdateParams ¶
type BillingInfoUpdateParams struct {
// Name sets the invoice name.
Name *string `json:"name,omitempty"`
// Address sets the invoice address.
Address *string `json:"address,omitempty"`
// BillingEmail sets the invoice email address.
BillingEmail *string `json:"billing_email,omitempty"`
}
BillingInfoUpdateParams are the parameters for BillingService.UpdateInfo. Only set fields are sent.
type BillingService ¶
type BillingService struct {
// contains filtered or unexported fields
}
BillingService exposes the billing information operations.
func (*BillingService) GetInfo ¶
func (s *BillingService) GetInfo(ctx context.Context, opts ...RequestOption) (*BillingInfo, error)
GetInfo returns the billing information associated with the account. There is exactly one billing information object per account.
func (*BillingService) UpdateInfo ¶
func (s *BillingService) UpdateInfo(ctx context.Context, params BillingInfoUpdateParams, opts ...RequestOption) (*BillingInfo, error)
UpdateInfo partially updates the billing information.
type CheckoutBehavior ¶
type CheckoutBehavior string
CheckoutBehavior selects how a purchased plan interacts with the subscription's existing plans.
const ( // BehaviorReplace replaces the old plan with the new one. Only // supported for subscriptions with a single plan. The default. BehaviorReplace CheckoutBehavior = "replace" // BehaviorAdd adds the plan to the subscription. BehaviorAdd CheckoutBehavior = "add" // BehaviorUpgrade upgrades the plan (used by the pricing endpoint). BehaviorUpgrade CheckoutBehavior = "upgrade" )
Checkout behaviors.
type Client ¶
type Client struct {
// Proxies exposes the proxy list operations.
Proxies *ProxiesService
// ProxyConfig exposes the proxy configuration operations.
ProxyConfig *ProxyConfigService
// ProxyReplacements exposes the proxy replacement operations.
ProxyReplacements *ProxyReplacementsService
// ReplacedProxies exposes the replaced proxy operations.
ReplacedProxies *ReplacedProxiesService
// Stats exposes the proxy usage statistics operations.
Stats *StatsService
// ProxyActivity exposes the proxy activity operations.
ProxyActivity *ProxyActivityService
// DownloadTokens exposes the download token operations.
DownloadTokens *DownloadTokensService
// IPAuthorizations exposes the IP authorization operations.
IPAuthorizations *IPAuthorizationsService
// Subusers exposes the sub-user operations.
Subusers *SubusersService
// Profile exposes the user profile operations.
Profile *ProfileService
// Notifications exposes the notification operations.
Notifications *NotificationsService
// IDVerification exposes the ID verification operations.
IDVerification *IDVerificationService
// Verification exposes the account verification operations.
Verification *VerificationService
// Billing exposes the billing information operations.
Billing *BillingService
// PaymentMethods exposes the payment method operations.
PaymentMethods *PaymentMethodsService
// PendingPayments exposes the pending payment operations.
PendingPayments *PendingPaymentsService
// Transactions exposes the transaction operations.
Transactions *TransactionsService
// Subscription exposes the subscription operations.
Subscription *SubscriptionService
// Plans exposes the plan operations.
Plans *PlansService
// Invoices exposes the invoice operations.
Invoices *InvoicesService
// Referral exposes the referral and coupon code operations.
Referral *ReferralService
// contains filtered or unexported fields
}
Client is the Webshare API client. Create one with NewClient. All API operations are grouped into resource services exposed as fields.
A Client is safe for concurrent use by multiple goroutines: its configuration is immutable after NewClient, and per-request options are applied to a copy.
func NewClient ¶
func NewClient(opts ...RequestOption) (*Client, error)
NewClient creates a Webshare API client. Credentials are taken from WithAPIKey or WithTokenSource; when neither is given, the WEBSHARE_API_KEY environment variable is used. NewClient returns an error when no credential is available (unless WithUnauthenticated is passed) or an option is invalid.
Example ¶
package main
import (
"context"
"fmt"
"log"
webshare "github.com/webshare-proxy/webshare-go"
)
func main() {
client, err := webshare.NewClient(webshare.WithAPIKey("your-api-key"))
if err != nil {
log.Fatal(err)
}
profile, err := client.Profile.Get(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Println(profile.Email)
}
Output:
type ConnectionMode ¶
type ConnectionMode string
ConnectionMode selects how proxies are accessed: connecting directly to the proxy address, or through the p.webshare.io backbone.
const ( // ModeDirect connects to the proxy_address and port returned by the // proxy list API. ModeDirect ConnectionMode = "direct" // ModeBackbone connects through p.webshare.io. Required when the plan's // pool_filter is residential. ModeBackbone ConnectionMode = "backbone" )
Connection modes.
type CouponCode ¶
type CouponCode struct {
// Code is the applied coupon code. Nil when no code is applied.
Code *string `json:"code"`
// PromoType is percent_off or value_off. Nil when no code is applied.
PromoType *CouponPromoType `json:"promo_type"`
// PromoValue is the discount magnitude as a decimal string. Nil when
// no code is applied.
PromoValue *string `json:"promo_value"`
// Description is the human-readable channel description. Nil when no
// code is applied.
Description *string `json:"description"`
// IsRecurring reports whether the discount applies to every renewal.
// Nil when no code is applied.
IsRecurring *bool `json:"is_recurring"`
}
CouponCode is the coupon code applied to the user. Every field is nil when no code is applied.
type CouponDiscount ¶
type CouponDiscount struct {
// Code is the applied coupon code.
Code string `json:"code"`
// PromoType is percent_off or value_off.
PromoType CouponPromoType `json:"promo_type"`
// PromoValue is the discount magnitude as a decimal string.
PromoValue string `json:"promo_value"`
// IsRecurring reports whether the discount applies to every renewal.
IsRecurring bool `json:"is_recurring"`
}
CouponDiscount summarizes the coupon code applied to the user.
type CouponPromoType ¶
type CouponPromoType string
CouponPromoType is the discount type of a coupon code or referral channel. This vocabulary is distinct from SubscriptionPromoType.
const ( // CouponPercentOff discounts a fraction of the price ("0.20" = 20%). CouponPercentOff CouponPromoType = "percent_off" // CouponValueOff discounts an absolute USD amount. CouponValueOff CouponPromoType = "value_off" )
Coupon promotion types.
type CrossOriginError ¶
type CrossOriginError struct {
// BaseOrigin is the scheme://host origin of the client base URL.
BaseOrigin string
// TargetOrigin is the scheme://host origin of the refused URL.
TargetOrigin string
}
CrossOriginError is returned when a URL taken from a response envelope (such as a pagination next link) points at a different origin than the client base URL. The SDK refuses to follow such URLs so credentials are never sent cross-origin.
func (*CrossOriginError) Error ¶
func (e *CrossOriginError) Error() string
Error implements the error interface.
type CustomizationFeature ¶
type CustomizationFeature struct {
// Feature is the feature name.
Feature string `json:"feature"`
// Required reports whether the feature is required.
Required bool `json:"required"`
}
CustomizationFeature is one selectable plan feature.
type CustomizationTerm ¶
type CustomizationTerm struct {
// Term is the term name.
Term SubscriptionTerm `json:"term"`
// RenewalsPaid is the number of renewals paid at once for the term.
RenewalsPaid int `json:"renewals_paid"`
}
CustomizationTerm is one available term option.
type DownloadToken ¶
type DownloadToken struct {
// ID is the unique identifier of the download token.
ID int `json:"id"`
// Key is the token value passed as the download_token query parameter.
Key string `json:"key"`
// Scope is what this token can download.
Scope DownloadTokenScope `json:"scope"`
// ExpireAt is when the token expires.
ExpireAt time.Time `json:"expire_at"`
}
DownloadToken authorizes record downloads for its scope until it expires.
type DownloadTokenScope ¶
type DownloadTokenScope string
DownloadTokenScope selects what a download token can download.
const ( // ScopeProxyList is the proxy_list download token scope. ScopeProxyList DownloadTokenScope = "proxy_list" // ScopeReplacedProxy is the replaced_proxy download token scope. ScopeReplacedProxy DownloadTokenScope = "replaced_proxy" // ScopeActivity is the activity download token scope. ScopeActivity DownloadTokenScope = "activity" )
Download token scopes.
type DownloadTokensService ¶
type DownloadTokensService struct {
// contains filtered or unexported fields
}
DownloadTokensService exposes the download token operations. Download tokens authorize the replaced proxy and activity download endpoints.
func (*DownloadTokensService) Get ¶
func (s *DownloadTokensService) Get(ctx context.Context, scope DownloadTokenScope, opts ...RequestOption) (*DownloadToken, error)
Get returns the download token for the given scope.
func (*DownloadTokensService) Reset ¶
func (s *DownloadTokensService) Reset(ctx context.Context, scope DownloadTokenScope, opts ...RequestOption) (*DownloadToken, error)
Reset rotates the download token for the given scope and returns the new token.
type EarnoutStatus ¶
type EarnoutStatus string
EarnoutStatus is the status of an earn-out.
const ( // EarnoutProcessing means the earn-out is being processed. EarnoutProcessing EarnoutStatus = "processing" // EarnoutCompleted means the earn-out completed. EarnoutCompleted EarnoutStatus = "completed" // EarnoutFailed means the earn-out failed; ErrorReason is set. EarnoutFailed EarnoutStatus = "failed" )
Earn-out statuses.
type Error ¶
type Error struct {
// StatusCode is the HTTP status code of the response.
StatusCode int
// Code is the machine-readable API error code when present (for example
// "2fa_needed", "account_suspended" or "account_deleted"). Empty when the
// response carried no code.
Code string
// RequestID is the value of the X-Request-ID response header when present.
RequestID string
// Detail is the human-readable error message.
Detail string
// FieldErrors maps field names to validation messages for request
// validation failures, e.g. {"mode": ["This field is required."]}.
FieldErrors map[string][]string
// Body is the raw response body, capped at 1 MiB.
Body []byte
// RetryAfter is the wait parsed from the Retry-After header (delta
// seconds or HTTP-date), when present and valid. Nil when the header was
// absent or unparsable. It is exposed so callers can self-throttle calls
// the SDK does not retry (for example a 429 on a POST).
RetryAfter *time.Duration
}
Error is returned when the Webshare API responds with a non-success status code. Use errors.As to inspect it:
var apiErr *webshare.Error
if errors.As(err, &apiErr) {
switch apiErr.Code {
case "2fa_needed":
// ...
}
}
type FeaturePrice ¶
type FeaturePrice struct {
// Feature is the feature name.
Feature string `json:"feature"`
// IsSelected reports whether the feature is part of the priced plan.
IsSelected bool `json:"is_selected"`
// Price is the feature price in USD.
Price float64 `json:"price"`
}
FeaturePrice is one feature's price in the pricing response.
type File ¶
type File struct {
// Name is the file name reported to the API.
Name string
// Reader supplies the file contents.
Reader io.Reader
}
File is a file to upload in a multipart request.
type IDVerification ¶
type IDVerification struct {
// ID is the unique identifier of this instance.
ID int `json:"id"`
// State is the state of the current ID verification.
State IDVerificationState `json:"state"`
// ClientSecret is used with the Stripe JS API. Nil unless the
// verification is pending.
ClientSecret *string `json:"client_secret"`
// VerificationFailureTimes counts failed ID verifications.
VerificationFailureTimes int `json:"verification_failure_times"`
// MaxVerificationFailureTimes is how many times a verification can fail
// before new attempts are blocked.
MaxVerificationFailureTimes int `json:"max_verification_failure_times"`
// CreatedAt is the original registration date.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the verification object was last updated.
UpdatedAt time.Time `json:"updated_at"`
// VerifiedAt is when the verification completed successfully. May be
// nil.
VerifiedAt *time.Time `json:"verified_at"`
}
IDVerification is the ID verification object of the account.
type IDVerificationService ¶
type IDVerificationService struct {
// contains filtered or unexported fields
}
IDVerificationService exposes the read-only ID verification status. Webshare uses Stripe Identity; verifications are completed from the dashboard.
func (*IDVerificationService) Get ¶
func (s *IDVerificationService) Get(ctx context.Context, opts ...RequestOption) (*IDVerification, error)
Get retrieves the ID verification object.
type IDVerificationState ¶
type IDVerificationState string
IDVerificationState is the state of the ID verification.
const ( // IDVerificationNotRequired means no ID verification is needed. IDVerificationNotRequired IDVerificationState = "not-required" // IDVerificationRequested means the account must verify via the // dashboard. IDVerificationRequested IDVerificationState = "requested" // IDVerificationPending means a verification was started and the client // secret is available for Stripe JS. IDVerificationPending IDVerificationState = "pending" // IDVerificationProcessing means Stripe is processing the verification. IDVerificationProcessing IDVerificationState = "processing" // IDVerificationFailed means the verification failed. IDVerificationFailed IDVerificationState = "failed" // IDVerificationVerified means the verification succeeded. IDVerificationVerified IDVerificationState = "verified" )
ID verification states.
type IPAuthorization ¶
type IPAuthorization struct {
// ID is the unique identifier of the IP authorization.
ID int `json:"id"`
// IPAddress is the authorized IP address.
IPAddress string `json:"ip_address"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// LastUsedAt is when this IP address was last used. May be nil.
LastUsedAt *time.Time `json:"last_used_at"`
}
IPAuthorization authorizes an IP address to use the proxies without username/password credentials.
type IPAuthorizationCreateParams ¶
type IPAuthorizationCreateParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int `json:"-"`
// IPAddress is the IP address to authorize. Required. The API returns a
// 400 error when the address is already authorized in the system.
IPAddress string `json:"ip_address"`
}
IPAuthorizationCreateParams are the parameters for IPAuthorizationsService.Create.
type IPAuthorizationGetParams ¶
type IPAuthorizationGetParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
IPAuthorizationGetParams are the optional parameters for IPAuthorizationsService.Get and Delete.
type IPAuthorizationListParams ¶
type IPAuthorizationListParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
IPAuthorizationListParams are the parameters for IPAuthorizationsService.List.
type IPAuthorizationsService ¶
type IPAuthorizationsService struct {
// contains filtered or unexported fields
}
IPAuthorizationsService exposes the IP authorization operations.
func (*IPAuthorizationsService) Create ¶
func (s *IPAuthorizationsService) Create(ctx context.Context, params IPAuthorizationCreateParams, opts ...RequestOption) (*IPAuthorization, error)
Create authorizes an IP address.
func (*IPAuthorizationsService) Delete ¶
func (s *IPAuthorizationsService) Delete(ctx context.Context, id int, params IPAuthorizationGetParams, opts ...RequestOption) error
Delete removes an IP authorization.
func (*IPAuthorizationsService) Get ¶
func (s *IPAuthorizationsService) Get(ctx context.Context, id int, params IPAuthorizationGetParams, opts ...RequestOption) (*IPAuthorization, error)
Get retrieves an IP authorization.
func (*IPAuthorizationsService) List ¶
func (s *IPAuthorizationsService) List(ctx context.Context, params IPAuthorizationListParams, opts ...RequestOption) (*Page[IPAuthorization], error)
List returns the IP authorizations in paginated format.
func (*IPAuthorizationsService) ListAll ¶
func (s *IPAuthorizationsService) ListAll(ctx context.Context, params IPAuthorizationListParams, opts ...RequestOption) iter.Seq2[IPAuthorization, error]
ListAll returns a lazy iterator over every IP authorization across all pages.
func (*IPAuthorizationsService) WhatsMyIP ¶
func (s *IPAuthorizationsService) WhatsMyIP(ctx context.Context, opts ...RequestOption) (*WhatsMyIPResult, error)
WhatsMyIP returns the caller's public IP address, useful before creating an IP authorization.
type InvoicesService ¶
type InvoicesService struct {
// contains filtered or unexported fields
}
InvoicesService exposes the invoice operations.
func (*InvoicesService) Download ¶
func (s *InvoicesService) Download(ctx context.Context, subscriptionTransactionID int, opts ...RequestOption) ([]byte, error)
Download returns the invoice for the given subscription transaction as PDF bytes. The ID is the Transaction.ID of a subscription payment.
type Notification ¶
type Notification struct {
// ID is the unique identifier of the notification.
ID int `json:"id"`
// Type is the notification type.
Type string `json:"type"`
// IsDismissable reports whether the notification can be dismissed.
IsDismissable bool `json:"is_dismissable"`
// Context carries additional type-specific context (for example plan,
// plan_limit, effect, projected_bandwidth_gbs).
Context map[string]any `json:"context"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
// DismissedAt is when the notification was dismissed. May be nil.
DismissedAt *time.Time `json:"dismissed_at"`
}
Notification is one account notification. Known types include too_much_bandwidth_too_little_proxies, unlimited_bandwidth_gets_throttled, subscription_renew_failed, subscription_cc_will_expire_soon, reminder_to_use_proxy, projected_proxy_usage_over_80, projected_proxy_usage_over_100, high_concurrency_error, 100_percent_bandwidth_used, proxies_are_unallocated and question_is_added.
type NotificationListParams ¶
type NotificationListParams struct {
// DismissedAtIsNull filters by dismissal state.
DismissedAtIsNull *bool
// Ordering orders by id, created_at or dismissed_at; the default is
// -created_at.
Ordering string
// Type filters by notification type.
Type string
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
NotificationListParams are the parameters for NotificationsService.List.
type NotificationsService ¶
type NotificationsService struct {
// contains filtered or unexported fields
}
NotificationsService exposes the notification (activity feed) operations.
func (*NotificationsService) Dismiss ¶
func (s *NotificationsService) Dismiss(ctx context.Context, id int, opts ...RequestOption) (*Notification, error)
Dismiss dismisses a notification and returns it with DismissedAt set.
func (*NotificationsService) Get ¶
func (s *NotificationsService) Get(ctx context.Context, id int, opts ...RequestOption) (*Notification, error)
Get retrieves a notification.
func (*NotificationsService) List ¶
func (s *NotificationsService) List(ctx context.Context, params NotificationListParams, opts ...RequestOption) (*Page[Notification], error)
List returns the account notifications in paginated format.
func (*NotificationsService) ListAll ¶
func (s *NotificationsService) ListAll(ctx context.Context, params NotificationListParams, opts ...RequestOption) iter.Seq2[Notification, error]
ListAll returns a lazy iterator over every notification across all pages.
func (*NotificationsService) Restore ¶
func (s *NotificationsService) Restore(ctx context.Context, id int, opts ...RequestOption) (*Notification, error)
Restore restores a dismissed notification and returns it with DismissedAt cleared.
type Nullable ¶
type Nullable[T any] struct { // contains filtered or unexported fields }
Nullable represents an optional request field that distinguishes between being omitted, set to an explicit JSON null, and set to a concrete value. The zero value is omitted from the request.
func NullableOf ¶
NullableOf returns a Nullable holding the given value.
func (Nullable[T]) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
type Page ¶
type Page[T any] struct { // Count is the total number of results across all pages. Count int `json:"count"` // Next is the URL of the next page, or nil on the last page. Next *string `json:"next"` // Previous is the URL of the previous page, or nil on the first page. Previous *string `json:"previous"` // Results holds the items on this page. Results []T `json:"results"` // contains filtered or unexported fields }
Page is one page of results from a paginated list endpoint. It exposes the raw pagination envelope and can fetch the following page.
func (*Page[T]) HasNextPage ¶
HasNextPage reports whether a further page is available.
type PaymentMethod ¶
type PaymentMethod struct {
// ID is the unique identifier of the payment method instance.
ID int `json:"id"`
// Type identifies the payment type, e.g. "StripeCard" or "LinkPayment".
Type PaymentMethodType `json:"type"`
// Brand is the card brand (StripeCard only).
Brand string `json:"brand,omitempty"`
// Last4 holds the last four digits of the card (StripeCard only).
Last4 string `json:"last4,omitempty"`
// Name is the cardholder name. May be nil.
Name *string `json:"name"`
// ExpirationYear is the card expiration year (StripeCard only).
ExpirationYear int `json:"expiration_year,omitempty"`
// ExpirationMonth is the card expiration month (StripeCard only).
ExpirationMonth int `json:"expiration_month,omitempty"`
// CreatedAt is when the payment method was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the payment method was last updated.
UpdatedAt time.Time `json:"updated_at"`
// Line is the billing address line.
Line string `json:"line,omitempty"`
// City is the billing address city.
City string `json:"city,omitempty"`
// State is the billing address state. May be nil.
State *string `json:"state"`
// PostalCode is the billing address postal code.
PostalCode string `json:"postal_code,omitempty"`
// Country is the billing address country.
Country string `json:"country,omitempty"`
}
PaymentMethod is a payment method associated with the account. Payment methods are polymorphic: discriminate on Type. The card fields (Brand, Last4, ExpirationYear, ExpirationMonth) are present only for StripeCard.
type PaymentMethodListParams ¶
type PaymentMethodListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
PaymentMethodListParams are the parameters for PaymentMethodsService.List.
type PaymentMethodType ¶
type PaymentMethodType string
PaymentMethodType identifies the kind of a payment method.
const ( // PaymentMethodStripeCard is a Stripe card payment method; it carries // the card-specific fields. PaymentMethodStripeCard PaymentMethodType = "StripeCard" // PaymentMethodLinkPayment is a Stripe Link payment method without // card-specific fields. PaymentMethodLinkPayment PaymentMethodType = "LinkPayment" )
Payment method types.
type PaymentMethodsService ¶
type PaymentMethodsService struct {
// contains filtered or unexported fields
}
PaymentMethodsService exposes the payment method operations.
func (*PaymentMethodsService) Get ¶
func (s *PaymentMethodsService) Get(ctx context.Context, id int, opts ...RequestOption) (*PaymentMethod, error)
Get retrieves a payment method. The active payment method ID is available on the subscription object.
func (*PaymentMethodsService) List ¶
func (s *PaymentMethodsService) List(ctx context.Context, params PaymentMethodListParams, opts ...RequestOption) (*Page[PaymentMethod], error)
List retrieves the payment methods in paginated format.
func (*PaymentMethodsService) ListAll ¶
func (s *PaymentMethodsService) ListAll(ctx context.Context, params PaymentMethodListParams, opts ...RequestOption) iter.Seq2[PaymentMethod, error]
ListAll returns a lazy iterator over every payment method across all pages.
type PendingPayment ¶
type PendingPayment struct {
// ID is the unique identifier of the pending payment object.
ID int `json:"id"`
// Status is the current state of the pending payment.
Status PendingPaymentStatus `json:"status"`
// FailureReason is a user-friendly message set when Status is failed.
// May be nil.
FailureReason *string `json:"failure_reason"`
// PaymentMethod is the ID of the payment method used.
PaymentMethod int `json:"payment_method"`
// Plan is the ID of the plan being paid for.
Plan int `json:"plan"`
// Transaction is the resulting transaction ID; only set when Status is
// successful. May be nil.
Transaction *int `json:"transaction"`
// IsRenewal reports whether the payment renews the subscription rather
// than immediately changing it.
IsRenewal bool `json:"is_renewal"`
// Term is the term of the payment.
Term SubscriptionTerm `json:"term"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
// CompletedAt is when the payment completed. May be nil.
CompletedAt *time.Time `json:"completed_at"`
}
PendingPayment links a payment attempt to a plan and payment method.
type PendingPaymentListParams ¶
type PendingPaymentListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
PendingPaymentListParams are the parameters for PendingPaymentsService.List.
type PendingPaymentStatus ¶
type PendingPaymentStatus string
PendingPaymentStatus is the state of a pending payment.
const ( // PendingPaymentPending means the payment was initiated. PendingPaymentPending PendingPaymentStatus = "pending" // PendingPaymentProcessing means the payment is being processed. PendingPaymentProcessing PendingPaymentStatus = "processing" // PendingPaymentSuccessful means the payment completed; Transaction is // set. PendingPaymentSuccessful PendingPaymentStatus = "successful" // PendingPaymentFailed means the payment failed; FailureReason is set. PendingPaymentFailed PendingPaymentStatus = "failed" )
Pending payment statuses.
type PendingPaymentsService ¶
type PendingPaymentsService struct {
// contains filtered or unexported fields
}
PendingPaymentsService exposes the pending payment operations. A pending payment is a payment that has been initiated but not yet completed; poll Get after confirming a Stripe payment to learn the outcome.
func (*PendingPaymentsService) Get ¶
func (s *PendingPaymentsService) Get(ctx context.Context, id int, opts ...RequestOption) (*PendingPayment, error)
Get retrieves a pending payment.
func (*PendingPaymentsService) List ¶
func (s *PendingPaymentsService) List(ctx context.Context, params PendingPaymentListParams, opts ...RequestOption) (*Page[PendingPayment], error)
List retrieves the pending payments in paginated format.
func (*PendingPaymentsService) ListAll ¶
func (s *PendingPaymentsService) ListAll(ctx context.Context, params PendingPaymentListParams, opts ...RequestOption) iter.Seq2[PendingPayment, error]
ListAll returns a lazy iterator over every pending payment across all pages.
type Plan ¶
type Plan struct {
// ID is the unique identifier of the plan instance.
ID int `json:"id"`
// Status is the plan status.
Status PlanStatus `json:"status"`
// BandwidthLimit is the bandwidth limit in GB. Zero means unlimited.
BandwidthLimit float64 `json:"bandwidth_limit"`
// MonthlyPrice is the USD price for the monthly term.
MonthlyPrice float64 `json:"monthly_price"`
// YearlyPrice is the USD price for the yearly term.
YearlyPrice float64 `json:"yearly_price"`
// ProxyType is the proxy category.
ProxyType ProxyType `json:"proxy_type"`
// ProxySubtype is the proxy sub-category.
ProxySubtype ProxySubtype `json:"proxy_subtype"`
// ProxyCount is the number of proxies in the plan.
ProxyCount int `json:"proxy_count"`
// ProxyCountries maps country code to proxy count; ZZ means randomly
// allocated.
ProxyCountries map[string]int `json:"proxy_countries"`
// RequiredSiteChecks lists site checks the proxy list must pass.
RequiredSiteChecks []string `json:"required_site_checks"`
// OnDemandRefreshesTotal is the number of on-demand refreshes purchased.
OnDemandRefreshesTotal int `json:"on_demand_refreshes_total"`
// OnDemandRefreshesUsed counts refreshes used since the subscription
// start date.
OnDemandRefreshesUsed int `json:"on_demand_refreshes_used"`
// OnDemandRefreshesAvailable is the number of refreshes available.
OnDemandRefreshesAvailable int `json:"on_demand_refreshes_available"`
// AutomaticRefreshFrequency refreshes the proxy list every N seconds.
// Zero means no automatic refreshes.
AutomaticRefreshFrequency int `json:"automatic_refresh_frequency"`
// AutomaticRefreshLastAt is the last automatic refresh. Nil in the list
// endpoint.
AutomaticRefreshLastAt *time.Time `json:"automatic_refresh_last_at"`
// AutomaticRefreshNextAt is the next automatic refresh. Nil in the list
// endpoint.
AutomaticRefreshNextAt *time.Time `json:"automatic_refresh_next_at"`
// ProxyReplacementsTotal is the number of proxy replacements purchased.
ProxyReplacementsTotal int `json:"proxy_replacements_total"`
// ProxyReplacementsUsed counts replacements used since the subscription
// start date.
ProxyReplacementsUsed int `json:"proxy_replacements_used"`
// ProxyReplacementsAvailable is the number of replacements available.
ProxyReplacementsAvailable int `json:"proxy_replacements_available"`
// SubusersTotal is the number of sub-users allowed in the plan.
SubusersTotal int `json:"subusers_total"`
// SubusersUsed is the number of sub-users in use.
SubusersUsed int `json:"subusers_used"`
// SubusersAvailable is the number of sub-users still available.
SubusersAvailable int `json:"subusers_available"`
// IsUnlimitedIPAuthorizations reports unlimited IP authorizations.
IsUnlimitedIPAuthorizations bool `json:"is_unlimited_ip_authorizations"`
// IsHighConcurrency reports high concurrency (3,000 concurrent
// requests).
IsHighConcurrency bool `json:"is_high_concurrency"`
// Is2XConcurrency reports 2x concurrency (1,000 concurrent requests).
Is2XConcurrency bool `json:"is_2x_concurrency"`
// IsHighPriorityNetwork reports the high priority network.
IsHighPriorityNetwork bool `json:"is_high_priority_network"`
// HighQualityIPsOnly reports whether only high quality IPs are used.
HighQualityIPsOnly bool `json:"high_quality_ips_only"`
// BundleInfo is set when the plan is a bundle addon. May be nil.
BundleInfo *PlanBundleInfo `json:"bundle_info"`
// BundleAddons lists addons when the plan is a bundle's primary plan.
BundleAddons []PlanBundleAddon `json:"bundle_addons"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
Plan is one plan created by the user, active or cancelled.
type PlanBundleAddon ¶
type PlanBundleAddon struct {
// PlanID is the ID of the addon plan.
PlanID int `json:"plan_id"`
// DiscountRate is the discount applied to the addon.
DiscountRate float64 `json:"discount_rate"`
}
PlanBundleAddon is one addon of a bundle's primary plan.
type PlanBundleInfo ¶
type PlanBundleInfo struct {
// PrimaryPlanID is the ID of the bundle's primary plan. May be nil.
PrimaryPlanID *int `json:"primary_plan_id"`
// DiscountRate is the discount applied to the plan, e.g. 0.2 for 20%.
DiscountRate float64 `json:"discount_rate"`
}
PlanBundleInfo is set when a plan is an addon in a bundle.
type PlanCancelResult ¶
type PlanCancelResult struct {
// Success reports whether the cancellation succeeded.
Success bool `json:"success"`
// Transaction is the ID of the credit transaction created by the
// cancellation.
Transaction int `json:"transaction"`
}
PlanCancelResult is the response of PlansService.Cancel.
type PlanConfiguration ¶
type PlanConfiguration struct {
// ProxyType is the proxy category.
ProxyType ProxyType `json:"proxy_type,omitempty"`
// ProxySubtype is the proxy sub-category.
ProxySubtype ProxySubtype `json:"proxy_subtype,omitempty"`
// ProxyCountries maps country code to proxy count; ZZ means randomly
// allocated.
ProxyCountries map[string]int `json:"proxy_countries,omitempty"`
// BandwidthLimit is the bandwidth limit in GB. Zero means unlimited.
BandwidthLimit float64 `json:"bandwidth_limit"`
// OnDemandRefreshesTotal is the number of on-demand refreshes purchased.
OnDemandRefreshesTotal int `json:"on_demand_refreshes_total"`
// AutomaticRefreshFrequency refreshes the proxy list every N seconds.
// Zero means no automatic refreshes.
AutomaticRefreshFrequency int `json:"automatic_refresh_frequency"`
// ProxyReplacementsTotal is the number of proxy replacements purchased.
ProxyReplacementsTotal int `json:"proxy_replacements_total"`
// SubusersTotal is the number of sub-users allowed.
SubusersTotal int `json:"subusers_total"`
// IsUnlimitedIPAuthorizations enables unlimited IP authorizations.
IsUnlimitedIPAuthorizations bool `json:"is_unlimited_ip_authorizations"`
// IsHighConcurrency enables high concurrency (3,000 concurrent
// requests).
IsHighConcurrency bool `json:"is_high_concurrency"`
// Is2XConcurrency enables 2x concurrency (1,000 concurrent requests).
Is2XConcurrency bool `json:"is_2x_concurrency"`
// IsHighPriorityNetwork enables the high priority network.
IsHighPriorityNetwork bool `json:"is_high_priority_network"`
// HighQualityIPsOnly restricts to high quality IPs with perfect fraud
// scores. Not available for residential plans; 30% price premium.
HighQualityIPsOnly bool `json:"high_quality_ips_only"`
// RequiredSiteChecks lists site checks the proxy list must pass.
RequiredSiteChecks []string `json:"required_site_checks,omitempty"`
// Term is the subscription term.
Term SubscriptionTerm `json:"term,omitempty"`
}
PlanConfiguration describes a plan being priced or purchased. It is shared by the pricing, purchase and upgrade endpoints.
type PlanListParams ¶
type PlanListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
PlanListParams are the parameters for PlansService.List.
type PlanStatus ¶
type PlanStatus string
PlanStatus is the status of a plan.
const ( // PlanActive is the account's active plan. PlanActive PlanStatus = "active" // PlanCancelled is a plan that is no longer active. PlanCancelled PlanStatus = "cancelled" )
Plan statuses.
type PlanUpdateParams ¶
type PlanUpdateParams struct {
// AutomaticRefreshNextAt sets the next automatic proxy list refresh.
AutomaticRefreshNextAt *time.Time `json:"automatic_refresh_next_at,omitempty"`
}
PlanUpdateParams are the parameters for PlansService.Update. Only the automatic refresh schedule is updatable.
type PlansService ¶
type PlansService struct {
// contains filtered or unexported fields
}
PlansService exposes the plan operations.
func (*PlansService) Cancel ¶
func (s *PlansService) Cancel(ctx context.Context, id int, opts ...RequestOption) (*PlanCancelResult, error)
Cancel cancels an existing plan, crediting the subscription for the duration and bandwidth left in the plan.
func (*PlansService) Get ¶
func (s *PlansService) Get(ctx context.Context, id int, opts ...RequestOption) (*Plan, error)
Get retrieves a plan. The active plan ID is available on the subscription object.
func (*PlansService) List ¶
func (s *PlansService) List(ctx context.Context, params PlanListParams, opts ...RequestOption) (*Page[Plan], error)
List retrieves all plans created by the user, including non-active ones, in paginated format.
func (*PlansService) ListAll ¶
func (s *PlansService) ListAll(ctx context.Context, params PlanListParams, opts ...RequestOption) iter.Seq2[Plan, error]
ListAll returns a lazy iterator over every plan across all pages.
func (*PlansService) Update ¶
func (s *PlansService) Update(ctx context.Context, id int, params PlanUpdateParams, opts ...RequestOption) (*Plan, error)
Update updates an existing plan. Only AutomaticRefreshNextAt can be updated.
type PricingTier ¶
type PricingTier struct {
// From is the exclusive lower bound of the tier.
From int `json:"from"`
// To is the inclusive upper bound of the tier. May be nil.
To *int `json:"to"`
// DiscountPercentage is the discount for the tier.
DiscountPercentage int `json:"discount_percentage"`
// PerProxyPrice is the price per proxy in the tier.
PerProxyPrice float64 `json:"per_proxy_price"`
// PerGBPrice is the price per GB in the tier. May be nil.
PerGBPrice *float64 `json:"per_gb_price"`
}
PricingTier is one discount tier of the pricing response. From is exclusive and To is inclusive; a nil To extends to infinity.
type Profile ¶
type Profile struct {
// ID is the unique identifier of the profile instance.
ID int `json:"id"`
// Email is the user's email address. Read-only.
Email string `json:"email"`
// FirstName is the user's first name. Can be empty.
FirstName string `json:"first_name"`
// LastName is the user's last name. Can be empty.
LastName string `json:"last_name"`
// LastLogin is the date the user last logged in. Read-only.
LastLogin time.Time `json:"last_login"`
// Timezone is the user's preferred timezone.
Timezone string `json:"timezone"`
// SubscribedBandwidthUsageNotifications toggles bandwidth usage emails.
SubscribedBandwidthUsageNotifications bool `json:"subscribed_bandwidth_usage_notifications"`
// SubscribedSubscriptionNotifications toggles subscription update
// emails.
SubscribedSubscriptionNotifications bool `json:"subscribed_subscription_notifications"`
// SubscribedProxyUsageStatistics toggles proxy usage statistics emails.
SubscribedProxyUsageStatistics bool `json:"subscribed_proxy_usage_statistics"`
// SubscribedUsageWarnings toggles proxy usage warning emails.
SubscribedUsageWarnings bool `json:"subscribed_usage_warnings"`
// SubscribedGuidesAndTips toggles guides-and-tips emails.
SubscribedGuidesAndTips bool `json:"subscribed_guides_and_tips"`
// SubscribedSurveyEmails toggles survey emails.
SubscribedSurveyEmails bool `json:"subscribed_survey_emails"`
// TrackingID is a unique user ID for identifying the user with external
// services. Read-only.
TrackingID string `json:"tracking_id"`
// AnnounceKitUserToken is a token for the AnnounceKit widget. Observed
// on the live API; absent from the documented object.
AnnounceKitUserToken string `json:"announce_kit_user_token,omitempty"`
// HelpscoutBeaconSignature is a signature for the Help Scout beacon.
// Observed on the live API; absent from the documented object.
HelpscoutBeaconSignature string `json:"helpscout_beacon_signature,omitempty"`
// IntercomSignature is a signature for the Intercom widget. Observed on
// the live API; absent from the documented object.
IntercomSignature string `json:"intercom_signature,omitempty"`
// IsVIPCustomer reports whether the account is a VIP customer. Observed
// on the live API; absent from the documented object.
IsVIPCustomer bool `json:"is_vip_customer,omitempty"`
// CreatedAt is the registration date. Read-only.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
Profile is the user profile of the account.
type ProfilePreferences ¶
type ProfilePreferences struct {
// ID is the unique identifier of the preferences instance.
ID int `json:"id"`
// CustomerSatisfactionSurveyLastDismissedAt is when the customer
// satisfaction survey was dismissed. May be nil.
CustomerSatisfactionSurveyLastDismissedAt *time.Time `json:"customer_satisfaction_survey_last_dismissed_at"`
// CustomerSatisfactionSurveyLastCompletedAt is when the customer
// satisfaction survey was completed. May be nil.
CustomerSatisfactionSurveyLastCompletedAt *time.Time `json:"customer_satisfaction_survey_last_completed_at"`
// OnboardingActivityPageViewedAt is when the onboarding activity page
// was viewed. May be nil.
OnboardingActivityPageViewedAt *time.Time `json:"onboarding_activity_page_viewed_at"`
// CreatedAt is when the preferences instance was created. Observed on
// the live API; absent from the documented object.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt is when the preferences instance was last updated. Observed
// on the live API; absent from the documented object.
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
ProfilePreferences are the user preferences of the account.
type ProfilePreferencesUpdateParams ¶
type ProfilePreferencesUpdateParams struct {
// CustomerSatisfactionSurveyLastDismissedAt records when the customer
// satisfaction survey was dismissed.
CustomerSatisfactionSurveyLastDismissedAt *time.Time `json:"customer_satisfaction_survey_last_dismissed_at,omitempty"`
// CustomerSatisfactionSurveyLastCompletedAt records when the customer
// satisfaction survey was completed.
CustomerSatisfactionSurveyLastCompletedAt *time.Time `json:"customer_satisfaction_survey_last_completed_at,omitempty"`
// OnboardingActivityPageViewedAt records when the onboarding activity
// page was viewed.
OnboardingActivityPageViewedAt *time.Time `json:"onboarding_activity_page_viewed_at,omitempty"`
}
ProfilePreferencesUpdateParams are the parameters for ProfileService.UpdatePreferences. Any subset of fields may be set.
type ProfileService ¶
type ProfileService struct {
// contains filtered or unexported fields
}
ProfileService exposes the user profile operations.
func (*ProfileService) Get ¶
func (s *ProfileService) Get(ctx context.Context, opts ...RequestOption) (*Profile, error)
Get retrieves the user profile.
func (*ProfileService) GetPreferences ¶
func (s *ProfileService) GetPreferences(ctx context.Context, opts ...RequestOption) (*ProfilePreferences, error)
GetPreferences retrieves the user preferences.
func (*ProfileService) Update ¶
func (s *ProfileService) Update(ctx context.Context, params ProfileUpdateParams, opts ...RequestOption) (*Profile, error)
Update partially updates the user profile.
func (*ProfileService) UpdatePreferences ¶
func (s *ProfileService) UpdatePreferences(ctx context.Context, params ProfilePreferencesUpdateParams, opts ...RequestOption) (*ProfilePreferences, error)
UpdatePreferences partially updates the user preferences.
type ProfileUpdateParams ¶
type ProfileUpdateParams struct {
// FirstName sets the user's first name.
FirstName *string `json:"first_name,omitempty"`
// LastName sets the user's last name.
LastName *string `json:"last_name,omitempty"`
// Timezone sets the user's preferred timezone.
Timezone *string `json:"timezone,omitempty"`
// SubscribedBandwidthUsageNotifications toggles bandwidth usage emails.
SubscribedBandwidthUsageNotifications *bool `json:"subscribed_bandwidth_usage_notifications,omitempty"`
// SubscribedSubscriptionNotifications toggles subscription update
// emails.
SubscribedSubscriptionNotifications *bool `json:"subscribed_subscription_notifications,omitempty"`
// SubscribedProxyUsageStatistics toggles proxy usage statistics emails.
SubscribedProxyUsageStatistics *bool `json:"subscribed_proxy_usage_statistics,omitempty"`
// SubscribedUsageWarnings toggles proxy usage warning emails.
SubscribedUsageWarnings *bool `json:"subscribed_usage_warnings,omitempty"`
// SubscribedGuidesAndTips toggles guides-and-tips emails.
SubscribedGuidesAndTips *bool `json:"subscribed_guides_and_tips,omitempty"`
// SubscribedSurveyEmails toggles survey emails.
SubscribedSurveyEmails *bool `json:"subscribed_survey_emails,omitempty"`
}
ProfileUpdateParams are the parameters for ProfileService.Update. Only set fields are sent.
type ProxiesService ¶
type ProxiesService struct {
// contains filtered or unexported fields
}
ProxiesService exposes the proxy list operations.
func (*ProxiesService) Download ¶
func (s *ProxiesService) Download(ctx context.Context, params ProxyDownloadParams, opts ...RequestOption) (string, error)
Download fetches the proxy list as plain text, one proxy per line in address:port:username:password format. This endpoint is unauthenticated (the URL embeds the download token); no Authorization header is sent.
func (*ProxiesService) DownloadURL ¶
func (s *ProxiesService) DownloadURL(params ProxyDownloadParams) (string, error)
DownloadURL builds the shareable path-style proxy list download URL without performing a request.
func (*ProxiesService) List ¶
func (s *ProxiesService) List(ctx context.Context, params ProxyListParams, opts ...RequestOption) (*Page[Proxy], error)
List returns the proxy list in paginated format. The Mode parameter is required.
func (*ProxiesService) ListAll ¶
func (s *ProxiesService) ListAll(ctx context.Context, params ProxyListParams, opts ...RequestOption) iter.Seq2[Proxy, error]
ListAll returns a lazy iterator over every proxy across all pages.
Example ¶
package main
import (
"context"
"fmt"
"log"
webshare "github.com/webshare-proxy/webshare-go"
)
func main() {
client, err := webshare.NewClient()
if err != nil {
log.Fatal(err)
}
for proxy, err := range client.Proxies.ListAll(context.Background(), webshare.ProxyListParams{Mode: webshare.ModeDirect}) {
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s (%s)\n", proxy.ID, proxy.CountryCode)
}
}
Output:
func (*ProxiesService) Refresh ¶
func (s *ProxiesService) Refresh(ctx context.Context, params ProxyRefreshParams, opts ...RequestOption) error
Refresh replaces the entire proxy list on demand. Only available when the plan has on_demand_refreshes_available.
type Proxy ¶
type Proxy struct {
// ID is the unique identifier of the proxy instance. Unlike other
// resources, proxy IDs are strings (for example "d-10513").
ID string `json:"id"`
// Username is the proxy username.
Username string `json:"username"`
// Password is the proxy password.
Password string `json:"password"`
// ProxyAddress is the IP address of the proxy. In direct connection mode
// connect to this address; in backbone mode connect to p.webshare.io.
// Nil when the plan's pool_filter is residential.
ProxyAddress *string `json:"proxy_address"`
// Port is the port used to connect to the proxy. In backbone mode the
// port is always set for IP authorization.
Port int `json:"port"`
// Valid reports whether the proxy is working as expected. Proxies are
// checked once every 30 seconds.
Valid bool `json:"valid"`
// LastVerification is the last time the proxy was checked.
LastVerification time.Time `json:"last_verification"`
// CountryCode is the ISO 3166-1 alpha-2 country code of the proxy.
CountryCode string `json:"country_code"`
// CityName is the city name of the proxy.
CityName string `json:"city_name"`
// ASNName is the ASN name of the proxy. Observed on the live API;
// absent from the documented object.
ASNName string `json:"asn_name,omitempty"`
// ASNNumber is the ASN number of the proxy. Observed on the live API;
// absent from the documented object.
ASNNumber int `json:"asn_number,omitempty"`
// HighCountryConfidence reports whether the proxy location has high
// country confidence. Observed on the live API; absent from the
// documented object.
HighCountryConfidence bool `json:"high_country_confidence,omitempty"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
}
Proxy is one entry of the proxy list.
type ProxyActivity ¶
type ProxyActivity struct {
// Timestamp is when the proxy request was made.
Timestamp time.Time `json:"timestamp"`
// Protocol is the proxy protocol: "http" or "socks".
Protocol string `json:"protocol"`
// RequestDuration is the total proxy request duration in seconds.
RequestDuration float64 `json:"request_duration"`
// HandshakeDuration is the seconds spent authenticating and
// establishing the proxy connection.
HandshakeDuration float64 `json:"handshake_duration"`
// TunnelDuration is the seconds the connection stayed active after the
// handshake. May be nil.
TunnelDuration *float64 `json:"tunnel_duration"`
// ErrorReason is the error reason for the proxy request. May be nil.
ErrorReason *string `json:"error_reason"`
// ErrorReasonHowToFix is a user-friendly explanation of how to fix the
// error. May be nil.
ErrorReasonHowToFix *string `json:"error_reason_how_to_fix"`
// AuthUsername is the proxy username used for this request. Only set
// when ErrorReason is no_proxies_allocated. May be nil.
AuthUsername *string `json:"auth_username"`
// ProxyAddress is the IP address of the proxy used to access the target
// site. Nil for residential plans.
ProxyAddress *string `json:"proxy_address"`
// Bytes is the number of bytes consumed by this proxy request.
Bytes float64 `json:"bytes"`
// ClientAddress is the IP address used to connect to the proxy server.
ClientAddress string `json:"client_address"`
// IPAddress is the IP address of the target site. May be nil.
IPAddress *string `json:"ip_address"`
// Hostname is the hostname of the target site. May be nil.
Hostname *string `json:"hostname"`
// Domain is the domain name of the target site. May be nil.
Domain *string `json:"domain"`
// Port is the port of the target site. May be nil.
Port *int `json:"port"`
// ProxyPort is the source port used to connect to the target site. May
// be nil.
ProxyPort *int `json:"proxy_port"`
// ListenAddress is the IP address of the proxy server connected to.
ListenAddress string `json:"listen_address"`
// ListenPort is the port of the proxy server connected to.
ListenPort int `json:"listen_port"`
}
ProxyActivity is one authenticated proxy request record.
type ProxyActivityDownloadParams ¶
type ProxyActivityDownloadParams struct {
// DownloadToken is the key obtained from DownloadTokens.Get with the
// activity scope. Required.
DownloadToken string
// TimestampLTE bounds activities to timestamps at or before this time.
TimestampLTE *time.Time
// TimestampGTE bounds activities to timestamps at or after this time.
TimestampGTE *time.Time
// Search is a generic search query.
Search string
// ErrorReason matches only requests with the given error reason. Pass
// "*" to match any request with an error.
ErrorReason string
// StartingAfter passes the timestamp of the last activity.
StartingAfter *time.Time
// BytesGTE filters requests with bytes at or above the given value.
BytesGTE string
// BytesLTE filters requests with bytes at or below the given value.
BytesLTE string
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
ProxyActivityDownloadParams are the parameters for ProxyActivityService.Download.
type ProxyActivityListParams ¶
type ProxyActivityListParams struct {
// TimestampLTE bounds activities to timestamps at or before this time.
TimestampLTE *time.Time
// TimestampGTE bounds activities to timestamps at or after this time.
// No older than 90 days.
TimestampGTE *time.Time
// Search is a generic search query.
Search string
// ErrorReason matches only requests with the given error reason. Pass
// "*" to match any request with an error.
ErrorReason string
// StartingAfter pages the list: pass the timestamp of the last activity
// to retrieve the next page.
StartingAfter *time.Time
// PageSize is the number of results per page.
PageSize *int
// BytesGTE filters requests with bytes at or above the given value.
BytesGTE string
// BytesLTE filters requests with bytes at or below the given value.
BytesLTE string
// VerificationCategory filters by an account verification category.
VerificationCategory string
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
ProxyActivityListParams are the parameters for ProxyActivityService.List.
type ProxyActivityService ¶
type ProxyActivityService struct {
// contains filtered or unexported fields
}
ProxyActivityService exposes the proxy activity operations.
func (*ProxyActivityService) Download ¶
func (s *ProxyActivityService) Download(ctx context.Context, params ProxyActivityDownloadParams, opts ...RequestOption) (string, error)
Download fetches the proxy activities as a CSV file (columns: Time, Hostname, Destination Port, Bytes, Duration, Proxy, Your IP Address, Error Reason, Protocol). This endpoint is unauthenticated (it uses the download token from the activity scope); no Authorization header is sent.
func (*ProxyActivityService) List ¶
func (s *ProxyActivityService) List(ctx context.Context, params ProxyActivityListParams, opts ...RequestOption) (*Page[ProxyActivity], error)
List returns the proxy activity within a time period. This endpoint paginates with starting_after and page_size instead of page numbers: pass the timestamp of the latest activity as StartingAfter to view the next page (NextPage and ListAll handle this automatically).
func (*ProxyActivityService) ListAll ¶
func (s *ProxyActivityService) ListAll(ctx context.Context, params ProxyActivityListParams, opts ...RequestOption) iter.Seq2[ProxyActivity, error]
ListAll returns a lazy iterator over every proxy activity across all pages.
type ProxyConfig ¶
type ProxyConfig struct {
// ID is the unique identifier of the proxy configuration instance.
ID int `json:"id"`
// State indicates whether the proxy list is ready to use.
State ProxyConfigState `json:"state"`
// Countries maps country code to proxy count in the proxy list.
Countries map[string]int `json:"countries"`
// AvailableCountries maps country code to proxy count available outside
// the current proxy list.
AvailableCountries map[string]int `json:"available_countries"`
// UnallocatedCountries maps country code to unallocated proxy count.
UnallocatedCountries map[string]int `json:"unallocated_countries"`
// IPRanges24 maps /24 CIDR to proxy count in the proxy list. Empty for
// residential plans.
IPRanges24 map[string]int `json:"ip_ranges_24"`
// IPRanges16 maps /16 CIDR to proxy count in the proxy list.
IPRanges16 map[string]int `json:"ip_ranges_16"`
// IPRanges8 maps /8 CIDR to proxy count in the proxy list.
IPRanges8 map[string]int `json:"ip_ranges_8"`
// AvailableIPRanges24 maps /24 CIDR to available proxy count.
AvailableIPRanges24 map[string]int `json:"available_ip_ranges_24"`
// AvailableIPRanges16 maps /16 CIDR to available proxy count.
AvailableIPRanges16 map[string]int `json:"available_ip_ranges_16"`
// AvailableIPRanges8 maps /8 CIDR to available proxy count.
AvailableIPRanges8 map[string]int `json:"available_ip_ranges_8"`
// ASNs maps ASN number to ASN name and count. Empty for residential
// plans.
ASNs map[string]ASNInfo `json:"asns"`
// AvailableASNs maps ASN number to ASN name and count for proxies
// available outside the current list.
AvailableASNs map[string]ASNInfo `json:"available_asns"`
// Username is the proxy username (8-32 characters, alphanumeric).
Username string `json:"username"`
// Password is the proxy password (8-32 characters, alphanumeric).
Password string `json:"password"`
// RequestTimeout is the maximum number of seconds a proxy request can be
// used.
RequestTimeout int `json:"request_timeout"`
// RequestIdleTimeout is the maximum number of seconds a proxy request
// can stay idle.
RequestIdleTimeout int `json:"request_idle_timeout"`
// IPAuthorizationCountryCodes lists country codes served for IP
// authorization in backbone mode. Nil means all countries.
IPAuthorizationCountryCodes []string `json:"ip_authorization_country_codes"`
// IPAuthorizationCity is the city for IP authorization geo targeting.
// Residential plans only. Nil when disabled.
IPAuthorizationCity *string `json:"ip_authorization_city"`
// IPAuthorizationState is the state for IP authorization geo targeting.
// Observed on the live API; only mentioned in passing in the docs. Nil
// when disabled.
IPAuthorizationState *string `json:"ip_authorization_state"`
// IPAuthorizationPostalCode is the postal code for IP authorization geo
// targeting. Observed on the live API; only mentioned in passing in the
// docs. Nil when disabled.
IPAuthorizationPostalCode *string `json:"ip_authorization_postalcode"`
// IPAuthorizationASN is the ASN targeted for IP authorization requests.
// Nil when disabled.
IPAuthorizationASN *string `json:"ip_authorization_asn"`
// AutoReplaceInvalidProxies replaces proxies invalid for 15 minutes.
AutoReplaceInvalidProxies bool `json:"auto_replace_invalid_proxies"`
// AutoReplaceLowCountryConfidenceProxies replaces proxies with low
// country confidence.
AutoReplaceLowCountryConfidenceProxies bool `json:"auto_replace_low_country_confidence_proxies"`
// AutoReplaceOutOfRotationProxies replaces proxies performing slower
// than usual.
AutoReplaceOutOfRotationProxies bool `json:"auto_replace_out_of_rotation_proxies"`
// AutoReplaceFailedSiteCheckProxies replaces proxies that no longer pass
// site checks.
AutoReplaceFailedSiteCheckProxies bool `json:"auto_replace_failed_site_check_proxies"`
// ProxyListDownloadToken is the token used in proxy list download links.
ProxyListDownloadToken string `json:"proxy_list_download_token"`
// IsProxyUsed indicates whether a proxy has been used.
IsProxyUsed bool `json:"is_proxy_used"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
ProxyConfig is the full proxy configuration object returned by the v2 update and allocate endpoints.
type ProxyConfigService ¶
type ProxyConfigService struct {
// contains filtered or unexported fields
}
ProxyConfigService exposes the proxy configuration operations.
func (*ProxyConfigService) AllocateUnallocatedCountries ¶
func (s *ProxyConfigService) AllocateUnallocatedCountries(ctx context.Context, params AllocateUnallocatedCountriesParams, opts ...RequestOption) (*ProxyConfig, error)
AllocateUnallocatedCountries allocates the proxies in unallocated_countries state and returns the full proxy config object.
func (*ProxyConfigService) Get ¶
func (s *ProxyConfigService) Get(ctx context.Context, planID int, opts ...RequestOption) (*ProxyConfigV3, error)
Get retrieves the proxy config (v3 endpoint). The plan ID is required.
func (*ProxyConfigService) GetStats ¶
func (s *ProxyConfigService) GetStats(ctx context.Context, planID int, opts ...RequestOption) (*ProxyListStats, error)
GetStats retrieves the proxy list composition (v3 endpoint). The plan ID is required. This is distinct from the usage statistics under Stats.
func (*ProxyConfigService) GetStatus ¶
func (s *ProxyConfigService) GetStatus(ctx context.Context, planID int, opts ...RequestOption) (*ProxyListStatus, error)
GetStatus retrieves the proxy status (v3 endpoint). The plan ID is required.
func (*ProxyConfigService) Update ¶
func (s *ProxyConfigService) Update(ctx context.Context, params ProxyConfigUpdateParams, opts ...RequestOption) (*ProxyConfig, error)
Update partially updates the proxy config (v2 endpoint) and returns the full proxy config object.
type ProxyConfigState ¶
type ProxyConfigState string
ProxyConfigState indicates whether a proxy list is ready to use.
const ( // ProxyConfigPending means the proxy list is not ready yet. ProxyConfigPending ProxyConfigState = "pending" // ProxyConfigProcessing means the proxy list is being prepared. ProxyConfigProcessing ProxyConfigState = "processing" // ProxyConfigCompleted means the proxy list is ready to use. ProxyConfigCompleted ProxyConfigState = "completed" )
Proxy configuration states.
type ProxyConfigUpdateParams ¶
type ProxyConfigUpdateParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
// Username sets the proxy username (8-32 characters, alphanumeric).
Username *string
// Password sets the proxy password (8-32 characters, alphanumeric).
Password *string
// RequestTimeout sets the maximum seconds a proxy request can be used.
RequestTimeout *int
// RequestIdleTimeout sets the maximum seconds a proxy request can idle.
RequestIdleTimeout *int
// IPAuthorizationCountryCodes sets the country codes served for IP
// authorization in backbone mode. Null means all countries.
IPAuthorizationCountryCodes Nullable[[]string]
// IPAuthorizationCity sets the city for IP authorization geo targeting
// (residential plans only). Null disables.
IPAuthorizationCity Nullable[string]
// IPAuthorizationState sets the state for IP authorization geo
// targeting. Mutually exclusive with the other geo filters. Null
// disables.
IPAuthorizationState Nullable[string]
// IPAuthorizationPostalCode sets the postal code for IP authorization
// geo targeting. Mutually exclusive with the other geo filters. Null
// disables.
IPAuthorizationPostalCode Nullable[string]
// IPAuthorizationASN sets the ASN for IP authorization targeting.
// Mutually exclusive with the other geo filters. Null disables.
IPAuthorizationASN Nullable[string]
// AutoReplaceInvalidProxies toggles replacing invalid proxies. Cannot be
// edited for free plans.
AutoReplaceInvalidProxies *bool
// AutoReplaceLowCountryConfidenceProxies toggles replacing proxies with
// low country confidence. Cannot be edited for free plans.
AutoReplaceLowCountryConfidenceProxies *bool
// AutoReplaceOutOfRotationProxies toggles replacing slow proxies.
AutoReplaceOutOfRotationProxies *bool
// AutoReplaceFailedSiteCheckProxies toggles replacing proxies failing
// site checks.
AutoReplaceFailedSiteCheckProxies *bool
}
ProxyConfigUpdateParams are the parameters for ProxyConfigService.Update. Only set fields are sent. The nullable geo-targeting fields accept an explicit null via webshare.Null to disable them.
func (ProxyConfigUpdateParams) MarshalJSON ¶
func (p ProxyConfigUpdateParams) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, sending only the set fields.
type ProxyConfigV3 ¶
type ProxyConfigV3 struct {
// RequestTimeout is the maximum number of seconds a proxy request can be
// used (min 15 seconds, max 7 days).
RequestTimeout int `json:"request_timeout"`
// RequestIdleTimeout is the maximum number of seconds a proxy request
// can stay idle (min 15 seconds, max 2 hours).
RequestIdleTimeout int `json:"request_idle_timeout"`
// IPAuthorizationCountryCodes lists country codes served for IP
// authorization in backbone mode. Nil means all countries.
IPAuthorizationCountryCodes []string `json:"ip_authorization_country_codes"`
// IPAuthorizationCity is the city for IP authorization geo targeting.
IPAuthorizationCity *string `json:"ip_authorization_city"`
// IPAuthorizationState is the state for IP authorization geo targeting.
// Observed on the live API; only mentioned in passing in the docs.
IPAuthorizationState *string `json:"ip_authorization_state"`
// IPAuthorizationPostalCode is the postal code for IP authorization geo
// targeting. Observed on the live API; only mentioned in passing in the
// docs.
IPAuthorizationPostalCode *string `json:"ip_authorization_postalcode"`
// IPAuthorizationASN is the ASN targeted for IP authorization requests.
IPAuthorizationASN *string `json:"ip_authorization_asn"`
// AutoReplaceInvalidProxies replaces proxies invalid for 15 minutes.
AutoReplaceInvalidProxies bool `json:"auto_replace_invalid_proxies"`
// AutoReplaceLowCountryConfidenceProxies replaces proxies with low
// country confidence.
AutoReplaceLowCountryConfidenceProxies bool `json:"auto_replace_low_country_confidence_proxies"`
// AutoReplaceOutOfRotationProxies replaces proxies performing slower
// than usual.
AutoReplaceOutOfRotationProxies bool `json:"auto_replace_out_of_rotation_proxies"`
// AutoReplaceFailedSiteCheckProxies replaces proxies that no longer pass
// site checks.
AutoReplaceFailedSiteCheckProxies bool `json:"auto_replace_failed_site_check_proxies"`
// ProxyListDownloadToken is the token used in proxy list download links.
ProxyListDownloadToken string `json:"proxy_list_download_token"`
}
ProxyConfigV3 is the editable/config subset returned by the v3 get endpoint. Counts, ranges and status live on GetStats and GetStatus.
type ProxyDownloadParams ¶
type ProxyDownloadParams struct {
// Token is the proxy_list_download_token from the proxy config API.
// Required.
Token string
// CountryCodes limits the download to the given ISO 3166-1 alpha-2
// country codes (validated, upper-cased and hyphen-joined in the URL).
// Empty means all countries.
CountryCodes []string
// Protocol fills the literal proxy protocol slot of the download path.
// Defaults to "any".
Protocol string
// AuthenticationMethod is AuthMethodUsername or AuthMethodSourceIP.
// Required.
AuthenticationMethod AuthenticationMethod
// EndpointMode is ModeDirect or ModeBackbone. Required. Must be
// ModeBackbone when the plan's pool_filter is residential.
EndpointMode ConnectionMode
// Search holds optional search terms. Empty means no search terms.
Search string
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
ProxyDownloadParams are the parameters for ProxiesService.Download and ProxiesService.DownloadURL.
type ProxyListParams ¶
type ProxyListParams struct {
// Mode must be ModeDirect or ModeBackbone. Required. Must be
// ModeBackbone when the plan's pool_filter is residential.
Mode ConnectionMode
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
// CountryCodeIn filters by ISO 3166-1 alpha-2 country codes.
CountryCodeIn []string
// Search filters by a search phrase. Does not work in backbone mode.
Search string
// Ordering is a comma separated list of ordering fields; prefix a field
// with "-" for descending order. Not supported in backbone mode.
Ordering string
// CreatedAt filters by proxy create date. Does not work in backbone mode.
CreatedAt string
// ProxyAddress filters by a specific proxy address. Does not work in
// backbone mode.
ProxyAddress string
// ProxyAddressIn filters by proxy addresses. Does not work in backbone
// mode.
ProxyAddressIn []string
// Valid filters by proxy validity. Does not work in backbone mode.
Valid *bool
// ASNNumber filters by the proxy ASN number. Does not work in backbone
// mode.
ASNNumber string
// ASNName filters by the proxy ASN name. Does not work in backbone mode.
ASNName string
}
ProxyListParams are the parameters for ProxiesService.List.
type ProxyListStats ¶
type ProxyListStats struct {
// AvailableCountries maps country code to available proxy count.
AvailableCountries map[string]int `json:"available_countries"`
// IPRanges24 maps /24 CIDR to proxy count in the proxy list.
IPRanges24 map[string]int `json:"ip_ranges_24"`
// IPRanges16 maps /16 CIDR to proxy count in the proxy list.
IPRanges16 map[string]int `json:"ip_ranges_16"`
// IPRanges8 maps /8 CIDR to proxy count in the proxy list.
IPRanges8 map[string]int `json:"ip_ranges_8"`
// AvailableIPRanges24 maps /24 CIDR to available proxy count.
AvailableIPRanges24 map[string]int `json:"available_ip_ranges_24"`
// AvailableIPRanges16 maps /16 CIDR to available proxy count.
AvailableIPRanges16 map[string]int `json:"available_ip_ranges_16"`
// AvailableIPRanges8 maps /8 CIDR to available proxy count.
AvailableIPRanges8 map[string]int `json:"available_ip_ranges_8"`
// ASNs maps ASN number to ASN name and count.
ASNs map[string]ASNInfo `json:"asns"`
// AvailableASNs maps ASN number to ASN name and count.
AvailableASNs map[string]ASNInfo `json:"available_asns"`
}
ProxyListStats is the proxy list composition returned by the v3 stats endpoint: available countries, IP ranges and ASNs of the current list.
type ProxyListStatus ¶
type ProxyListStatus struct {
// State indicates whether the proxy list is ready to use.
State ProxyConfigState `json:"state"`
// Countries maps country code to proxy count in the proxy list.
Countries map[string]int `json:"countries"`
// UnallocatedCountries maps country code to unallocated proxy count.
UnallocatedCountries map[string]int `json:"unallocated_countries"`
// Username is the proxy username.
Username string `json:"username"`
// Password is the proxy password.
Password string `json:"password"`
// IsProxyUsed indicates whether a proxy has been used.
IsProxyUsed bool `json:"is_proxy_used"`
}
ProxyListStatus is the proxy list readiness state returned by the v3 status endpoint.
type ProxyRefreshParams ¶
type ProxyRefreshParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
ProxyRefreshParams are the parameters for ProxiesService.Refresh.
type ProxyReplacement ¶
type ProxyReplacement struct {
// ID is the unique identifier of the proxy replacement instance.
ID int `json:"id"`
// ToReplace indicates which proxies to replace.
ToReplace ReplacementTarget `json:"to_replace"`
// ReplaceWith indicates which proxies to replace them with.
ReplaceWith []ReplacementTarget `json:"replace_with"`
// DryRun reports whether this replacement only computes the counts
// without modifying the proxy list.
DryRun bool `json:"dry_run"`
// State is the replacement lifecycle state.
State ReplacementState `json:"state"`
// ProxiesRemoved is the number of proxies removed from the proxy list.
ProxiesRemoved *int `json:"proxies_removed"`
// ProxiesAdded is the number of proxies added to the proxy list.
ProxiesAdded *int `json:"proxies_added"`
// Reason is why the proxies were replaced.
Reason ReplacementReason `json:"reason"`
// ErrorCode is set when State is ReplacementFailed.
ErrorCode *string `json:"error_code"`
// Error is the error message when State is ReplacementFailed.
Error *string `json:"error"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// DryRunCompletedAt is when the state became validated. May be nil.
DryRunCompletedAt *time.Time `json:"dry_run_completed_at"`
// CompletedAt is when the state became completed. May be nil.
CompletedAt *time.Time `json:"completed_at"`
}
ProxyReplacement is an asynchronous proxy replacement request.
type ProxyReplacementCreateParams ¶
type ProxyReplacementCreateParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int `json:"-"`
// ToReplace indicates which proxies to replace. Required.
ToReplace ReplacementTarget `json:"to_replace"`
// ReplaceWith indicates which proxies to replace them with. The
// ip_address type cannot be used here. Required.
ReplaceWith []ReplacementTarget `json:"replace_with"`
// DryRun computes proxies removed/added without modifying the list.
DryRun bool `json:"dry_run,omitempty"`
}
ProxyReplacementCreateParams are the parameters for ProxyReplacementsService.Create.
type ProxyReplacementGetParams ¶
type ProxyReplacementGetParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
ProxyReplacementGetParams are the optional parameters for ProxyReplacementsService.Get.
type ProxyReplacementListParams ¶
type ProxyReplacementListParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
// Ordering orders by id (default), created_at or completed_at.
Ordering string
// DryRun filters replacements by whether they are dry runs.
DryRun *bool
// State filters replacements by state.
State ReplacementState
}
ProxyReplacementListParams are the parameters for ProxyReplacementsService.List.
type ProxyReplacementsService ¶
type ProxyReplacementsService struct {
// contains filtered or unexported fields
}
ProxyReplacementsService exposes the proxy replacement operations (v3 endpoints).
func (*ProxyReplacementsService) Create ¶
func (s *ProxyReplacementsService) Create(ctx context.Context, params ProxyReplacementCreateParams, opts ...RequestOption) (*ProxyReplacement, error)
Create starts a proxy replacement. This is an asynchronous API: it returns a replacement in the validating state; poll Get until it reaches completed (or failed). Not available when the plan's pool_filter is residential.
func (*ProxyReplacementsService) Get ¶
func (s *ProxyReplacementsService) Get(ctx context.Context, id int, params ProxyReplacementGetParams, opts ...RequestOption) (*ProxyReplacement, error)
Get retrieves a proxy replacement. Use it to poll the state of a replacement created with Create.
func (*ProxyReplacementsService) List ¶
func (s *ProxyReplacementsService) List(ctx context.Context, params ProxyReplacementListParams, opts ...RequestOption) (*Page[ProxyReplacement], error)
List retrieves the proxy replacements in paginated format.
func (*ProxyReplacementsService) ListAll ¶
func (s *ProxyReplacementsService) ListAll(ctx context.Context, params ProxyReplacementListParams, opts ...RequestOption) iter.Seq2[ProxyReplacement, error]
ListAll returns a lazy iterator over every proxy replacement across all pages.
type ProxyStat ¶
type ProxyStat struct {
// Timestamp is the start of the one-hour aggregation window.
Timestamp time.Time `json:"timestamp"`
// IsProjected indicates whether the stat is projected rather than real.
IsProjected bool `json:"is_projected"`
// BandwidthTotal is the total bandwidth use in bytes for the window.
BandwidthTotal int64 `json:"bandwidth_total"`
// BandwidthAverage is the average bandwidth in bytes per request.
BandwidthAverage int64 `json:"bandwidth_average"`
// RequestsTotal is the number of proxy requests made.
RequestsTotal int64 `json:"requests_total"`
// RequestsSuccessful is the number of successful proxy requests.
RequestsSuccessful int64 `json:"requests_successful"`
// RequestsFailed is the number of failed proxy requests.
RequestsFailed int64 `json:"requests_failed"`
// ErrorReasons lists the error reasons. Empty when IsProjected is true.
ErrorReasons []StatErrorReason `json:"error_reasons"`
// CountriesUsed maps country code to request count. Empty when
// IsProjected is true.
CountriesUsed map[string]int64 `json:"countries_used"`
// NumberOfProxiesUsed is the estimated number of unique proxy addresses
// used. Zero when IsProjected is true.
NumberOfProxiesUsed int `json:"number_of_proxies_used"`
// ProtocolsUsed maps proxy protocol (http, socks) to request count.
// Empty when IsProjected is true.
ProtocolsUsed map[string]int64 `json:"protocols_used"`
// AverageConcurrency is the estimated average number of concurrent
// proxy requests. Nil when IsProjected is true.
AverageConcurrency *float64 `json:"average_concurrency"`
// AverageRPS is the estimated average proxy requests per second. Nil
// when IsProjected is true.
AverageRPS *float64 `json:"average_rps"`
// LastRequestSentAt is when the last proxy request in the window was
// sent. Nil when IsProjected is true.
LastRequestSentAt *time.Time `json:"last_request_sent_at"`
}
ProxyStat is one hourly aggregate of proxy usage.
type ProxyState ¶
type ProxyState string
ProxyState describes the verification limit applied to the account's proxies.
const ( // ProxyStateActive means proxies work normally. ProxyStateActive ProxyState = "active" // ProxyStateLimited means proxies are slower than usual and may error. ProxyStateLimited ProxyState = "limited" // ProxyStatePaused means proxies are currently not working. ProxyStatePaused ProxyState = "paused" )
Proxy states.
type ProxySubtype ¶
type ProxySubtype string
ProxySubtype is the sub-category of proxies in a plan. Not all proxy types have the same subtypes.
const ( // SubtypeDefault is the default proxy subtype. SubtypeDefault ProxySubtype = "default" // SubtypePremium is the premium proxy subtype. SubtypePremium ProxySubtype = "premium" // SubtypeISP is the ISP proxy subtype. SubtypeISP ProxySubtype = "isp" // SubtypeResidential is the residential proxy subtype. SubtypeResidential ProxySubtype = "residential" // SubtypeDatacenterAndISP is the datacenter-and-ISP proxy subtype. SubtypeDatacenterAndISP ProxySubtype = "datacenter_and_isp" )
Proxy subtypes.
type ProxyType ¶
type ProxyType string
ProxyType is the category of proxies in a plan.
const ( // ProxyTypeFree is the free proxy category. ProxyTypeFree ProxyType = "free" ProxyTypeShared ProxyType = "shared" // ProxyTypeSemidedicated is the semi-dedicated proxy category. ProxyTypeSemidedicated ProxyType = "semidedicated" // ProxyTypeDedicated is the dedicated proxy category. ProxyTypeDedicated ProxyType = "dedicated" )
Proxy types.
type ProxyURLParams ¶
type ProxyURLParams struct {
// Mode is the connection mode: ModeDirect or ModeBackbone. Required.
Mode ConnectionMode
// Scheme is the URL scheme, "http" by default.
Scheme string
// Username is the proxy username. Leave empty together with Password to
// build an IP-authorization URL without credentials.
Username string
// Password is the proxy password. Required when Username is set.
Password string
// Address is the proxy host. Required in direct mode; defaults to
// BackboneHost in backbone mode.
Address string
// Port is the proxy port. Required in direct mode; defaults to 80 in
// backbone mode.
Port int
// CountryCodes appends ISO 3166-1 alpha-2 country codes to the backbone
// username (lowercased). Backbone username/password auth only.
CountryCodes []string
// City appends a city_{name} parameter to the backbone username. Letters
// and underscores only; city targeting is available on residential plans.
City string
// SessionID appends a numeric sticky-session ID to the backbone
// username. Mutually exclusive with Rotate.
SessionID string
// Rotate appends the rotate parameter to the backbone username so every
// request uses a new IP. Mutually exclusive with SessionID.
Rotate bool
}
ProxyURLParams describes a proxy connection for ProxyURL.
type ReferralChannel ¶
type ReferralChannel struct {
// ID is the unique identifier of the referral channel.
ID int `json:"id"`
// Code is the coupon code other users apply. Matched
// case-insensitively.
Code string `json:"code"`
// Description is the human-readable channel description.
Description string `json:"description"`
// PromoType is percent_off or value_off.
PromoType CouponPromoType `json:"promo_type"`
// PromoValue is the discount magnitude as a decimal string.
PromoValue string `json:"promo_value"`
// IsActive reports whether new users can still apply the code.
IsActive bool `json:"is_active"`
// IsRecurring reports whether the discount applies to every renewal.
IsRecurring bool `json:"is_recurring"`
// StartDate is when the code becomes applicable.
StartDate time.Time `json:"start_date"`
// EndDate is when the code stops being applicable. May be nil for
// non-expiring channels.
EndDate *time.Time `json:"end_date"`
// TotalUses is the number of distinct redemptions across all users.
TotalUses int `json:"total_uses"`
// TotalCommission is the total USD commission earned through the
// channel.
TotalCommission float64 `json:"total_commission"`
// TotalRevenue is the total USD revenue generated by redeemers, net of
// refunds.
TotalRevenue float64 `json:"total_revenue"`
// InitialRate is the commission rate (0-1, decimal string) during the
// initial period.
InitialRate string `json:"initial_rate"`
// OngoingRate is the commission rate (0-1, decimal string) after the
// initial period.
OngoingRate string `json:"ongoing_rate"`
// InitialRatePeriodDays is the length of the initial commission period
// in days.
InitialRatePeriodDays int `json:"initial_rate_period_days"`
// MaxEarningsPerReferred is the maximum USD commission (decimal
// string) earnable from a single referred user.
MaxEarningsPerReferred string `json:"max_earnings_per_referred"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
}
ReferralChannel is a coupon code owned by the user, created and configured by the Webshare team.
type ReferralCodeInfo ¶
type ReferralCodeInfo struct {
// ReferralCode is the referral code.
ReferralCode string `json:"referral_code"`
// PromoType is the promotion type. May be nil.
PromoType *SubscriptionPromoType `json:"promo_type"`
// PromoValue is the promotion value (10 or 20). Nil when PromoType is
// nil.
PromoValue *int `json:"promo_value"`
}
ReferralCodeInfo is the publicly available information of a referral code.
type ReferralConfig ¶
type ReferralConfig struct {
// ID is the unique identifier of the referral config instance.
ID int `json:"id"`
// Mode selects payout or credits mode.
Mode ReferralMode `json:"mode"`
// PayPalPayoutEmail is the PayPal address receiving payouts. May be nil
// in credits mode; must be set in payout mode.
PayPalPayoutEmail *string `json:"paypal_payout_email"`
// IDVerificationRequired reports whether ID verification must be
// completed before a payout.
IDVerificationRequired bool `json:"id_verification_required"`
// CreditsEarned is the USD pending conversion to account credits at the
// next earn-out.
CreditsEarned float64 `json:"credits_earned"`
// PayoutsEarned is the USD pending payout to PayPal at the next
// earn-out.
PayoutsEarned float64 `json:"payouts_earned"`
// TotalCreditsEarned is the total credits earned so far.
TotalCreditsEarned float64 `json:"total_credits_earned"`
// TotalPayoutsEarned is the total payouts earned so far.
TotalPayoutsEarned float64 `json:"total_payouts_earned"`
// NumberOfUsersReferred is the number of unique users referred.
NumberOfUsersReferred int `json:"number_of_users_referred"`
// NumberOfUsersUpgraded is the number of unique referred users who
// upgraded.
NumberOfUsersUpgraded int `json:"number_of_users_upgraded"`
// EarnOutFrequency is the earn-out frequency in Django duration format
// ("[DD] [HH:MM:SS]").
EarnOutFrequency string `json:"earn_out_frequency"`
// NextEarnOutDate is when pending earnings are next converted or paid.
NextEarnOutDate time.Time `json:"next_earn_out_date"`
// MinimumEarnOutAmount is the minimum USD required for an earn-out.
MinimumEarnOutAmount float64 `json:"minimum_earn_out_amount"`
// ReferralCode is the user's unique referral code.
ReferralCode string `json:"referral_code"`
// ReferralURL is an example referral URL to the Webshare home page.
ReferralURL string `json:"referral_url"`
// ReferralMaximumCredits is the maximum credits or payouts earnable
// from a single referral.
ReferralMaximumCredits float64 `json:"referral_maximum_credits"`
// ReferralCreditRatio is the ratio of earnings per referral purchase
// (0.25 means $25 per $100 spend).
ReferralCreditRatio float64 `json:"referral_credit_ratio"`
// ReferralPaymentPendingDays is the grace period before a referral
// credit becomes available, in Django duration format.
ReferralPaymentPendingDays string `json:"referral_payment_pending_days"`
// PromoType is the promotion type referrals receive. May be nil.
PromoType *SubscriptionPromoType `json:"promo_type"`
// PromoValue is the promotion value (10 or 20). Nil when PromoType is
// nil.
PromoValue *int `json:"promo_value"`
// InitialRate is the commission rate (0-1) applied to a referred
// user's transactions during the initial period. Observed on the live
// API; absent from the documented object.
InitialRate float64 `json:"initial_rate,omitempty"`
// OngoingRate is the commission rate (0-1) applied after the initial
// period. Observed on the live API; absent from the documented object.
OngoingRate float64 `json:"ongoing_rate,omitempty"`
// InitialRatePeriodDays is the length in days of the initial
// commission period. Observed on the live API; absent from the
// documented object.
InitialRatePeriodDays int `json:"initial_rate_period_days,omitempty"`
// MaxEarningsPerReferred is the maximum USD commission earnable from a
// single referred user. Observed on the live API; absent from the
// documented object.
MaxEarningsPerReferred float64 `json:"max_earnings_per_referred,omitempty"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
ReferralConfig is the referral configuration of the account.
type ReferralConfigUpdateParams ¶
type ReferralConfigUpdateParams struct {
// Mode selects payout or credits mode.
Mode ReferralMode
// PayPalPayoutEmail sets the PayPal payout address; it must be set when
// Mode is payout.
PayPalPayoutEmail Nullable[string]
}
ReferralConfigUpdateParams are the parameters for ReferralService.UpdateConfig. Only Mode and PayPalPayoutEmail are writable.
func (ReferralConfigUpdateParams) MarshalJSON ¶
func (p ReferralConfigUpdateParams) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, sending only the set fields.
type ReferralCredit ¶
type ReferralCredit struct {
// ID is the unique identifier of the referral credit instance.
ID int `json:"id"`
// UserID is the referred user who spent money on Webshare.
UserID int `json:"user_id"`
// Mode is whether the credit is in payout or credits mode.
Mode string `json:"mode"`
// Amount is the amount earned in USD.
Amount float64 `json:"amount"`
// Status is the credit status; it becomes available after the
// referral payment pending period.
Status ReferralCreditStatus `json:"status"`
// ReferralChannel is the channel that produced the credit. Nil for
// credits earned through a referral link.
ReferralChannel *int `json:"referral_channel"`
// ReferralChannelCode is the code of the producing channel. Nil for
// credits earned through a referral link.
ReferralChannelCode *string `json:"referral_channel_code"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
// RevertedAt is when the credit was reverted. Nil unless Status is
// reverted.
RevertedAt *time.Time `json:"reverted_at"`
}
ReferralCredit is one credit earned from a referral's spend.
type ReferralCreditListParams ¶
type ReferralCreditListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
// Mode filters by payout or credits.
Mode ReferralMode
// Status filters by credit status.
Status ReferralCreditStatus
// ReferralChannel filters by the ID of an owned referral channel.
ReferralChannel *int
// Ordering orders by id, mode, amount, status, created_at, updated_at
// or reverted_at; prefix with "-" for descending order.
Ordering string
}
ReferralCreditListParams are the parameters for ReferralService.ListCredits.
type ReferralCreditStatus ¶
type ReferralCreditStatus string
ReferralCreditStatus is the status of a referral credit.
const ( // CreditPending means the credit is inside the grace period. CreditPending ReferralCreditStatus = "pending" // CreditAvailable means the credit is available. CreditAvailable ReferralCreditStatus = "available" // CreditReverted means the referral payment was reversed and the // credit reverted. CreditReverted ReferralCreditStatus = "reverted" )
Referral credit statuses.
type ReferralEarnout ¶
type ReferralEarnout struct {
// ID is the unique identifier of the earn-out instance.
ID int `json:"id"`
// Mode is whether the earn-out is a payout or credits.
Mode string `json:"mode"`
// PayPalPayoutEmail is the PayPal address that received the funds in
// payout mode. May be nil.
PayPalPayoutEmail *string `json:"paypal_payout_email"`
// Amount is the amount earned out in USD.
Amount float64 `json:"amount"`
// Status is the earn-out status.
Status EarnoutStatus `json:"status"`
// ErrorReason describes the failure when Status is failed. May be nil.
ErrorReason *string `json:"error_reason"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
ReferralEarnout is one conversion of pending referral earnings into account credits or a PayPal payout.
type ReferralEarnoutListParams ¶
type ReferralEarnoutListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
ReferralEarnoutListParams are the parameters for ReferralService.ListEarnouts.
type ReferralMode ¶
type ReferralMode string
ReferralMode is whether referral earnings convert to account credits or PayPal payouts.
const ( // ReferralModePayout sends earn-outs to the PayPal account. ReferralModePayout ReferralMode = "payout" // ReferralModeCredits converts earn-outs to account credits. ReferralModeCredits ReferralMode = "credits" )
Referral modes.
type ReferralService ¶
type ReferralService struct {
// contains filtered or unexported fields
}
ReferralService exposes the referral, affiliate and coupon code operations.
func (*ReferralService) ApplyCouponCode ¶
func (s *ReferralService) ApplyCouponCode(ctx context.Context, code string, opts ...RequestOption) (*CouponCode, error)
ApplyCouponCode applies a coupon code to the user, replacing any previously applied code. Documented 400 error codes: not_found, code_inactive, code_expired, self_referral, already_redeemed. This endpoint has its own rate limit of 5 requests per minute per user.
func (*ReferralService) GetCodeInfo ¶
func (s *ReferralService) GetCodeInfo(ctx context.Context, referralCode string, opts ...RequestOption) (*ReferralCodeInfo, error)
GetCodeInfo retrieves the public information of a referral code. This is the only unauthenticated endpoint in the referral group; no Authorization header is sent.
func (*ReferralService) GetConfig ¶
func (s *ReferralService) GetConfig(ctx context.Context, opts ...RequestOption) (*ReferralConfig, error)
GetConfig retrieves the referral config. Switching to the affiliate program via the API indicates consent to the affiliate agreement.
func (*ReferralService) GetCouponCode ¶
func (s *ReferralService) GetCouponCode(ctx context.Context, opts ...RequestOption) (*CouponCode, error)
GetCouponCode retrieves the coupon code currently applied to the user. At most one coupon code can be applied at a time.
func (*ReferralService) GetCredit ¶
func (s *ReferralService) GetCredit(ctx context.Context, id int, opts ...RequestOption) (*ReferralCredit, error)
GetCredit retrieves a referral credit.
func (*ReferralService) GetEarnout ¶
func (s *ReferralService) GetEarnout(ctx context.Context, id int, opts ...RequestOption) (*ReferralEarnout, error)
GetEarnout retrieves an earn-out.
func (*ReferralService) ListAllCredits ¶
func (s *ReferralService) ListAllCredits(ctx context.Context, params ReferralCreditListParams, opts ...RequestOption) iter.Seq2[ReferralCredit, error]
ListAllCredits returns a lazy iterator over every referral credit across all pages.
func (*ReferralService) ListAllEarnouts ¶
func (s *ReferralService) ListAllEarnouts(ctx context.Context, params ReferralEarnoutListParams, opts ...RequestOption) iter.Seq2[ReferralEarnout, error]
ListAllEarnouts returns a lazy iterator over every earn-out across all pages.
func (*ReferralService) ListChannels ¶
func (s *ReferralService) ListChannels(ctx context.Context, opts ...RequestOption) ([]ReferralChannel, error)
ListChannels returns the referral channels owned by the user. This endpoint is not paginated: it returns a plain array ordered by ID ascending.
func (*ReferralService) ListCredits ¶
func (s *ReferralService) ListCredits(ctx context.Context, params ReferralCreditListParams, opts ...RequestOption) (*Page[ReferralCredit], error)
ListCredits returns the referral credits in paginated format.
func (*ReferralService) ListEarnouts ¶
func (s *ReferralService) ListEarnouts(ctx context.Context, params ReferralEarnoutListParams, opts ...RequestOption) (*Page[ReferralEarnout], error)
ListEarnouts returns the earn-outs in paginated format.
func (*ReferralService) RemoveCouponCode ¶
func (s *ReferralService) RemoveCouponCode(ctx context.Context, opts ...RequestOption) error
RemoveCouponCode removes the coupon code currently applied to the user. Already-redeemed codes are not affected.
func (*ReferralService) UpdateConfig ¶
func (s *ReferralService) UpdateConfig(ctx context.Context, params ReferralConfigUpdateParams, opts ...RequestOption) (*ReferralConfig, error)
UpdateConfig updates the referral config.
type ReplacedProxiesService ¶
type ReplacedProxiesService struct {
// contains filtered or unexported fields
}
ReplacedProxiesService exposes the replaced proxy operations.
func (*ReplacedProxiesService) Download ¶
func (s *ReplacedProxiesService) Download(ctx context.Context, params ReplacedProxyDownloadParams, opts ...RequestOption) (string, error)
Download fetches the replaced proxy list as plain text; each line is new_address:new_port:username:password:replaced_address. This endpoint is unauthenticated (it uses the download token from the replaced_proxy scope); no Authorization header is sent.
func (*ReplacedProxiesService) List ¶
func (s *ReplacedProxiesService) List(ctx context.Context, params ReplacedProxyListParams, opts ...RequestOption) (*Page[ReplacedProxy], error)
List returns the replaced proxy list in paginated format.
func (*ReplacedProxiesService) ListAll ¶
func (s *ReplacedProxiesService) ListAll(ctx context.Context, params ReplacedProxyListParams, opts ...RequestOption) iter.Seq2[ReplacedProxy, error]
ListAll returns a lazy iterator over every replaced proxy across all pages.
type ReplacedProxy ¶
type ReplacedProxy struct {
// ID is the unique identifier of the replaced proxy instance.
ID int `json:"id"`
// Reason is why this proxy was replaced.
Reason ReplacementReason `json:"reason"`
// Proxy is the IP address of the replaced proxy.
Proxy string `json:"proxy"`
// ProxyPort is the port of the replaced proxy.
ProxyPort int `json:"proxy_port"`
// ProxyCountryCode is the country code of the replaced proxy.
ProxyCountryCode string `json:"proxy_country_code"`
// ReplacedWith is the IP address of the new proxy.
ReplacedWith string `json:"replaced_with"`
// ReplacedWithPort is the port of the new proxy.
ReplacedWithPort int `json:"replaced_with_port"`
// ReplacedWithCountryCode is the country code of the new proxy.
ReplacedWithCountryCode string `json:"replaced_with_country_code"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
}
ReplacedProxy records one proxy that was replaced in the proxy list.
type ReplacedProxyDownloadParams ¶
type ReplacedProxyDownloadParams struct {
// DownloadToken is the key obtained from DownloadTokens.Get with the
// replaced_proxy scope. Required.
DownloadToken string
// CountryCodes limits the download to the given ISO 3166-1 alpha-2
// country codes (validated, upper-cased and hyphen-joined). Empty means
// all countries.
CountryCodes []string
// AuthenticationType is AuthMethodUsername or AuthMethodSourceIP.
AuthenticationType AuthenticationMethod
// Mode is ModeDirect or ModeBackbone. Must be ModeBackbone when the
// plan's pool_filter is residential.
Mode ConnectionMode
// Search holds optional search terms.
Search string
// ProxyListReplacement filters by a specific proxy replacement ID.
ProxyListReplacement *int
// ProxyProtocol fills the proxy protocol query parameter, typically
// "any".
ProxyProtocol string
}
ReplacedProxyDownloadParams are the parameters for ReplacedProxiesService.Download.
type ReplacedProxyListParams ¶
type ReplacedProxyListParams struct {
// ProxyListReplacement filters by a specific proxy replacement ID.
ProxyListReplacement *int
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
ReplacedProxyListParams are the parameters for ReplacedProxiesService.List.
type ReplacementReason ¶
type ReplacementReason string
ReplacementReason explains why proxies were replaced.
const ( // ReasonListUpdated means the proxy list was updated. ReasonListUpdated ReplacementReason = "list_updated" // ReasonProxyReplaced means a replacement was created manually. ReasonProxyReplaced ReplacementReason = "proxy_replaced" // ReasonAutoInvalidated means invalid proxies were auto-replaced. ReasonAutoInvalidated ReplacementReason = "auto_invalidated" // ReasonAutoOutOfRotation means slow proxies were auto-replaced. ReasonAutoOutOfRotation ReplacementReason = "auto_out_of_rotation" // ReasonAutoLowCountryConfidence means proxies with low country // confidence were auto-replaced. ReasonAutoLowCountryConfidence ReplacementReason = "auto_low_country_confidence" // ReasonAutoDeleted means deleted proxies were auto-replaced. ReasonAutoDeleted ReplacementReason = "auto_deleted" // ReasonAutoSiteCheck means proxies failing site checks were // auto-replaced. ReasonAutoSiteCheck ReplacementReason = "auto_site_check" )
Replacement reasons.
type ReplacementState ¶
type ReplacementState string
ReplacementState is the lifecycle state of a proxy replacement.
const ( // ReplacementValidating means the dry run is in progress. ReplacementValidating ReplacementState = "validating" // ReplacementValidated means the dry run finished. ReplacementValidated ReplacementState = "validated" // ReplacementProcessing means the actual replacement is in progress. ReplacementProcessing ReplacementState = "processing" // ReplacementCompleted means the actual replacement finished. ReplacementCompleted ReplacementState = "completed" // ReplacementFailed means the replacement failed; ErrorCode and Error // are set. ReplacementFailed ReplacementState = "failed" )
Proxy replacement states.
type ReplacementTarget ¶
type ReplacementTarget struct {
// Type discriminates the target kind. Required.
Type ReplacementTargetType `json:"type"`
// IPRanges holds CIDR ranges for the ip_range type. Host bits may not
// be set (10.0.0.0/24 is valid, 10.0.0.1/24 is not).
IPRanges []string `json:"ip_ranges,omitempty"`
// IPAddresses holds IP addresses for the ip_address type.
IPAddresses []string `json:"ip_addresses,omitempty"`
// ASNNumbers holds ASN numbers for the asn type.
ASNNumbers []ASNNumber `json:"asn_numbers,omitempty"`
// CountryCode holds the country code for the country type.
CountryCode string `json:"country_code,omitempty"`
// Count limits how many proxies the target matches.
Count *int `json:"count,omitempty"`
}
ReplacementTarget selects which proxies to replace, or what to replace them with, depending on Type. Unused selector fields are omitted.
type ReplacementTargetType ¶
type ReplacementTargetType string
ReplacementTargetType discriminates ReplacementTarget values.
const ( // ReplacementTargetIPRange targets proxies by CIDR ranges. ReplacementTargetIPRange ReplacementTargetType = "ip_range" // ReplacementTargetIPAddress targets proxies by IP address. Valid only // in ToReplace, not in ReplaceWith. ReplacementTargetIPAddress ReplacementTargetType = "ip_address" // ReplacementTargetASN targets proxies by ASN numbers. ReplacementTargetASN ReplacementTargetType = "asn" // ReplacementTargetCountry targets proxies by country code. ReplacementTargetCountry ReplacementTargetType = "country" // ReplacementTargetAny targets any proxies. Valid only in ReplaceWith. ReplacementTargetAny ReplacementTargetType = "any" )
Replacement target types.
type RequestError ¶
type RequestError struct {
// Err is the underlying transport error.
Err error
}
RequestError is returned when a request could not be completed at the transport level (connection failures, timeouts, cancellation). It wraps the underlying error for use with errors.Is and errors.Unwrap.
func (*RequestError) Error ¶
func (e *RequestError) Error() string
Error implements the error interface.
func (*RequestError) Unwrap ¶
func (e *RequestError) Unwrap() error
Unwrap returns the underlying transport error.
type RequestOption ¶
type RequestOption func(*requestConfig)
RequestOption configures a Client or an individual request. Every option can be passed to NewClient to set a default for all requests, and most can also be passed to any API method to override the client-level setting for that single call.
func WithAPIKey ¶
func WithAPIKey(key string) RequestOption
WithAPIKey authenticates requests with the given Webshare API key. It is shorthand for WithTokenSource(StaticTokenSource(Token{Value: key})). An empty key is treated as absent: the client falls back to the WEBSHARE_API_KEY environment variable and then errors.
func WithBaseURL ¶
func WithBaseURL(rawURL string) RequestOption
WithBaseURL overrides the API base URL. The default is "https://proxy.webshare.io" (the bare host: every operation path carries its full /api/vN/... prefix). The URL must carry a scheme and a host.
func WithFederatedUser ¶
func WithFederatedUser(id int64) RequestOption
WithFederatedUser adds the X-Webshare-Federated-Access header so requests retrieve data as the given user. This is an admin-only feature.
func WithHTTPClient ¶
func WithHTTPClient(hc *http.Client) RequestOption
WithHTTPClient sets the *http.Client used to execute requests. The client must not be nil.
func WithHeader ¶
func WithHeader(key, value string) RequestOption
WithHeader adds an extra header to requests.
func WithMaxRetries ¶
func WithMaxRetries(n int) RequestOption
WithMaxRetries sets how many times a failed request is retried (default 2, meaning up to 3 attempts in total). Retries apply to connection errors, timeouts and 408/429/5xx responses on idempotent requests.
func WithRetryNonIdempotent ¶
func WithRetryNonIdempotent() RequestOption
WithRetryNonIdempotent opts non-idempotent requests (POST and PATCH) into the retry policy. By default only GET, PUT and DELETE requests are retried.
func WithSource ¶
func WithSource(source string) RequestOption
WithSource replaces the X-Webshare-Source header value that identifies the caller for API-side tracking. The default is "WebshareSDK/<version> (Go; <runtime version>)"; products built on the SDK (such as a CLI) can send their own product string instead.
func WithSubuser ¶
func WithSubuser(id int64) RequestOption
WithSubuser adds the X-Subuser header so that proxy configuration, proxy list, proxy stats and proxy activity calls act on behalf of the given sub-user.
func WithTimeout ¶
func WithTimeout(d time.Duration) RequestOption
WithTimeout sets the timeout for a single request attempt (default 60s). A zero or negative duration disables the timeout.
func WithTokenSource ¶
func WithTokenSource(ts TokenSource) RequestOption
WithTokenSource sets the credential provider used to authenticate requests. Use this to plug in dynamic credentials such as OAuth tokens.
func WithUnauthenticated ¶
func WithUnauthenticated() RequestOption
WithUnauthenticated constructs a client without credentials: NewClient neither requires a key nor reads WEBSHARE_API_KEY. Only unauthenticated operations (referral code info and the tokenized download endpoints) can be called; authenticated operations fail with a clear client-side error until credentials are provided. Passed to an individual call, it strips the client's credentials from that request.
type ResponseDecodeError ¶
type ResponseDecodeError struct {
// StatusCode is the HTTP status code of the response.
StatusCode int
// Body is the raw response body, capped at 1 MiB.
Body []byte
// Err is the underlying decode error.
Err error
}
ResponseDecodeError is returned when a success (2xx) response body cannot be decoded as the expected JSON shape, for example a non-JSON body or a malformed pagination envelope. It carries the status and the raw body (capped at 1 MiB) so callers never see a bare JSON error.
func (*ResponseDecodeError) Error ¶
func (e *ResponseDecodeError) Error() string
Error implements the error interface. The body is rendered as a short snippet; the capped raw body remains available on Body.
func (*ResponseDecodeError) Unwrap ¶
func (e *ResponseDecodeError) Unwrap() error
Unwrap returns the underlying decode error.
type SiteCheck ¶
type SiteCheck struct {
// Name is the site check name.
Name string `json:"name"`
}
SiteCheck is one available site check.
type StatErrorReason ¶
type StatErrorReason struct {
// Reason is the error code. The same code is present in the
// X-Webshare-Error-Reason header on failed proxied requests.
Reason string `json:"reason"`
// Type is "configuration" or "connection".
Type string `json:"type"`
// HowToFix is an end-user guide for fixing the error.
HowToFix string `json:"how_to_fix"`
// HTTPStatus is the status the proxy endpoint may return for this
// error. May be nil.
HTTPStatus *int `json:"http_status"`
// Count is the number of failed proxy requests with this reason.
Count int `json:"count"`
}
StatErrorReason describes one class of failed proxy requests within a stats window.
type StatsListParams ¶
type StatsListParams struct {
// TimestampLTE bounds stats to timestamps at or before this time. A
// future time includes projected stats. Cannot be after the
// subscription end date.
TimestampLTE *time.Time
// TimestampGTE bounds stats to timestamps at or after this time. Must
// be before TimestampLTE and no older than 90 days.
TimestampGTE *time.Time
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
StatsListParams are the parameters for StatsService.List and StatsService.Aggregate.
type StatsService ¶
type StatsService struct {
// contains filtered or unexported fields
}
StatsService exposes the proxy usage statistics operations.
func (*StatsService) Aggregate ¶
func (s *StatsService) Aggregate(ctx context.Context, params StatsListParams, opts ...RequestOption) (*AggregateStats, error)
Aggregate returns the proxy stats aggregated over the given period.
func (*StatsService) List ¶
func (s *StatsService) List(ctx context.Context, params StatsListParams, opts ...RequestOption) ([]ProxyStat, error)
List returns the hourly proxy stats within a time period. This endpoint is not paginated: it returns a bare array. Hours without proxy usage have no entry.
type SubmitAnswerParams ¶
type SubmitAnswerParams struct {
// Answer is the answer to the question.
Answer string
// Files lists optional attachments to submit with the answer.
Files []File
}
SubmitAnswerParams are the parameters for VerificationQuestionsService.SubmitAnswer.
type SubmitEvidenceParams ¶
type SubmitEvidenceParams struct {
// Explanation is the explanation submitted as part of the verification.
Explanation string
// Files lists the files submitted as part of the verification.
Files []File
}
SubmitEvidenceParams are the parameters for VerificationFlowsService.SubmitEvidence.
type SubmitSecurityCodeParams ¶
type SubmitSecurityCodeParams struct {
// SecurityCode is the two-character code found in Webshare charges on
// the user's bank statement.
SecurityCode string `json:"security_code"`
}
SubmitSecurityCodeParams are the parameters for VerificationFlowsService.SubmitSecurityCode.
type Subscription ¶
type Subscription struct {
// ID is the unique identifier of the subscription instance; it does not
// change for the user.
ID int `json:"id"`
// Plan is the ID of the active plan instance; it changes whenever the
// user re-customizes their plan.
Plan int `json:"plan"`
// PaymentMethod is the ID of the payment method on file. Nil when
// auto-renewal is cancelled.
PaymentMethod *int `json:"payment_method"`
// FreeCredits is the free credits available for the account in USD.
FreeCredits float64 `json:"free_credits"`
// Term determines the amount charged at the next renewal.
Term SubscriptionTerm `json:"term"`
// StartDate is the start of the current renewal term. The difference
// between end and start dates is always 30 days, even on yearly terms.
StartDate time.Time `json:"start_date"`
// EndDate is the end of the current renewal term.
EndDate time.Time `json:"end_date"`
// RenewalsPaid is the number of 30-day renewals paid. Yearly terms pay
// for 12 renewals at once.
RenewalsPaid int `json:"renewals_paid"`
// RenewalsEnabled reports whether auto-renewal is enabled.
RenewalsEnabled bool `json:"renewals_enabled"`
// FailedPaymentTimes counts failed automated renewal payments.
FailedPaymentTimes int `json:"failed_payment_times"`
// AccountDiscountPercentage is the discount percentage for the account.
AccountDiscountPercentage int `json:"account_discount_percentage"`
// PromotionAvailableFirstTimeRenewal25Off reports whether the 25% off
// first renewal promotion is available.
PromotionAvailableFirstTimeRenewal25Off bool `json:"promotion_available_first_time_renewal_25_off"`
// Customizable reports whether the subscription is customizable.
Customizable bool `json:"customizable"`
// Paused reports whether the subscription is paused.
Paused bool `json:"paused"`
// ReactivationDate is when a paused subscription resumes. May be nil.
ReactivationDate *time.Time `json:"reactivation_date"`
// ReactivationPeriodLeft is the period left in a paused subscription.
// May be nil.
ReactivationPeriodLeft *string `json:"reactivation_period_left"`
// PromoType is the promotion type for the account. May be nil.
PromoType *SubscriptionPromoType `json:"promo_type"`
// PromoValue is the promotion value (10 or 20). Nil when PromoType is
// nil.
PromoValue *int `json:"promo_value"`
// Throttled reports whether the subscription is throttled, usually due
// to high bandwidth usage with few proxies.
Throttled bool `json:"throttled"`
// WillRenew reports whether the subscription will renew at the end of
// the current term. Observed on the live API; absent from the
// documented object.
WillRenew bool `json:"will_renew,omitempty"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
Subscription is the subscription object of the account.
type SubscriptionCustomization ¶
type SubscriptionCustomization struct {
// ProxyType is the proxy category the options apply to.
ProxyType ProxyType `json:"proxy_type"`
// ProxySubtype is the proxy sub-category the options apply to.
ProxySubtype ProxySubtype `json:"proxy_subtype"`
// ProxyCountMax is the maximum number of proxies.
ProxyCountMax int `json:"proxy_count_max"`
// ProxyCountMin is the minimum number of proxies.
ProxyCountMin int `json:"proxy_count_min"`
// AvailableCountries maps country code to available proxy count.
AvailableCountries map[string]int `json:"available_countries"`
// OnDemandRefreshesMax is the maximum number of on-demand refreshes.
OnDemandRefreshesMax int `json:"on_demand_refreshes_max"`
// OnDemandRefreshesMin is the minimum number of on-demand refreshes.
OnDemandRefreshesMin int `json:"on_demand_refreshes_min"`
// AutomaticRefreshFrequencyMax is the maximum refresh frequency in
// seconds.
AutomaticRefreshFrequencyMax int `json:"automatic_refresh_frequency_max"`
// AutomaticRefreshFrequencyMin is the minimum refresh frequency in
// seconds.
AutomaticRefreshFrequencyMin int `json:"automatic_refresh_frequency_min"`
// ProxyReplacementsMax is the maximum number of proxy replacements.
ProxyReplacementsMax int `json:"proxy_replacements_max"`
// ProxyReplacementsMin is the minimum number of proxy replacements.
ProxyReplacementsMin int `json:"proxy_replacements_min"`
// BandwidthLimitMax is the maximum bandwidth limit in GB.
BandwidthLimitMax int `json:"bandwidth_limit_max"`
// BandwidthLimitMin is the minimum bandwidth limit in GB.
BandwidthLimitMin int `json:"bandwidth_limit_min"`
// SubusersMax is the maximum number of sub-users.
SubusersMax int `json:"subusers_max"`
// SubusersMin is the minimum number of sub-users.
SubusersMin int `json:"subusers_min"`
// AvailableFeatures lists the plan features that can be selected.
AvailableFeatures []CustomizationFeature `json:"available_features"`
// AvailableSiteChecks lists the site checks that can be required.
AvailableSiteChecks []SiteCheck `json:"available_site_checks"`
// Terms lists the available terms and their renewals paid.
Terms []CustomizationTerm `json:"terms"`
}
SubscriptionCustomization describes the limits and options available when customizing a plan.
type SubscriptionCustomizeParams ¶
type SubscriptionCustomizeParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int `json:"-"`
// ProxyType is the proxy category.
ProxyType ProxyType `json:"proxy_type,omitempty"`
// ProxySubtype is the proxy sub-category.
ProxySubtype ProxySubtype `json:"proxy_subtype,omitempty"`
// ProxyCountries maps country code to proxy count; ZZ means randomly
// allocated. Other customizations are based on this field.
ProxyCountries map[string]int `json:"proxy_countries,omitempty"`
// RequiredSiteChecks lists site checks the proxy list must pass.
RequiredSiteChecks []string `json:"required_site_checks,omitempty"`
// HighQualityIPsOnly restricts to high quality IPs. Not available for
// residential plans.
HighQualityIPsOnly *bool `json:"high_quality_ips_only,omitempty"`
}
SubscriptionCustomizeParams are the parameters for SubscriptionService.Customize. On the wire the request is JSON encoded into a single "query" GET parameter; the SDK handles that.
type SubscriptionPricing ¶
type SubscriptionPricing struct {
// DiscountPercentage is the percentage discount applied to the final
// price.
DiscountPercentage int `json:"discount_percentage"`
// NonDiscountedPrice is the original price before discounts.
NonDiscountedPrice float64 `json:"non_discounted_price"`
// Price is the price after discounts.
Price float64 `json:"price"`
// PaidToday is the amount to be paid today, after credits.
PaidToday float64 `json:"paid_today"`
// PromoDiscount is the USD value of the promo discount applied to the
// price.
PromoDiscount float64 `json:"promo_discount"`
// CreditsAdded is the credits added to make this subscription change.
CreditsAdded float64 `json:"credits_added"`
// CreditsUsed is the total credits used to change the subscription.
CreditsUsed float64 `json:"credits_used"`
// ProxyCountDiscountTiers lists per-proxy discount tiers.
ProxyCountDiscountTiers []PricingTier `json:"proxy_count_discount_tiers"`
// BandwidthDiscountTiers lists per-GB price tiers.
BandwidthDiscountTiers []PricingTier `json:"bandwidth_discount_tiers"`
// Features lists the features and their prices.
Features []FeaturePrice `json:"features"`
// TaxBreakdown lists tax entries when WithTax was requested.
TaxBreakdown []TaxEntry `json:"tax_breakdown"`
// CouponDiscount summarizes the applied coupon code. May be nil.
CouponDiscount *CouponDiscount `json:"coupon_discount"`
}
SubscriptionPricing is the pricing of a custom plan.
type SubscriptionPricingParams ¶
type SubscriptionPricingParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int `json:"-"`
// Behavior selects replace (default), add or upgrade.
Behavior CheckoutBehavior `json:"behavior,omitempty"`
// PlanConfiguration describes the plan being priced.
PlanConfiguration
// WithTax includes a tax breakdown in the response.
WithTax bool `json:"with_tax,omitempty"`
}
SubscriptionPricingParams are the parameters for SubscriptionService.Pricing. On the wire the request is JSON encoded into a single "query" GET parameter; the SDK handles that.
type SubscriptionPromoType ¶
type SubscriptionPromoType string
SubscriptionPromoType is the type of promotion applied to a subscription or referral.
const ( // PromoFirstTimeValueOff discounts a fixed value off the first // purchase. PromoFirstTimeValueOff SubscriptionPromoType = "first_time_value_off" // PromoFirstTimePercentOff discounts a percentage off the first // purchase. PromoFirstTimePercentOff SubscriptionPromoType = "first_time_percent_off" // PromoAlwaysValueOff discounts a fixed value off every purchase. PromoAlwaysValueOff SubscriptionPromoType = "always_value_off" // PromoAlwaysPercentOff discounts a percentage off every purchase. PromoAlwaysPercentOff SubscriptionPromoType = "always_percent_off" )
Subscription promotion types.
type SubscriptionService ¶
type SubscriptionService struct {
// contains filtered or unexported fields
}
SubscriptionService exposes the subscription operations. Each account has exactly one subscription with a stable ID; a new plan object is created every time the customer re-customizes.
func (*SubscriptionService) CancelAutoRenewal ¶
func (s *SubscriptionService) CancelAutoRenewal(ctx context.Context, opts ...RequestOption) (*Subscription, error)
CancelAutoRenewal cancels auto-renewal for the subscription and removes the payment method on file. Auto-renewal cannot be modified for free plans. Unlike most DELETE endpoints it returns 200 with the subscription object (RenewalsEnabled false, PaymentMethod nil).
func (*SubscriptionService) Customize ¶
func (s *SubscriptionService) Customize(ctx context.Context, params SubscriptionCustomizeParams, opts ...RequestOption) (*SubscriptionCustomization, error)
Customize returns the limits and options available to customize a plan.
func (*SubscriptionService) EnableAutoRenewal ¶
func (s *SubscriptionService) EnableAutoRenewal(ctx context.Context, opts ...RequestOption) (*Subscription, error)
EnableAutoRenewal enables auto-renewal for the subscription. A payment method must already be on file. Auto-renewal cannot be modified for free plans. Returns the subscription with RenewalsEnabled set to true.
func (*SubscriptionService) Get ¶
func (s *SubscriptionService) Get(ctx context.Context, opts ...RequestOption) (*Subscription, error)
Get returns the subscription object associated with the account.
func (*SubscriptionService) GetAvailableAssets ¶
func (s *SubscriptionService) GetAvailableAssets(ctx context.Context, opts ...RequestOption) (map[string]map[string]AssetInfo, error)
GetAvailableAssets returns the available assets for each proxy category. The result maps proxy category (shared, semidedicated, dedicated) to proxy subtype to asset info.
func (*SubscriptionService) Pricing ¶
func (s *SubscriptionService) Pricing(ctx context.Context, params SubscriptionPricingParams, opts ...RequestOption) (*SubscriptionPricing, error)
Pricing returns the pricing for a custom plan.
type SubscriptionTerm ¶
type SubscriptionTerm string
SubscriptionTerm is the renewal term of a subscription or payment.
const ( // TermMonthly pays for one 30-day renewal at a time. TermMonthly SubscriptionTerm = "monthly" // TermYearly pays for twelve 30-day renewals at once. TermYearly SubscriptionTerm = "yearly" )
Subscription terms.
type Subuser ¶
type Subuser struct {
// ID is the unique identifier of the sub-user. It never changes and is
// never reused.
ID int `json:"id"`
// Label identifies the sub-user.
Label string `json:"label"`
// ProxyCountries maps country code to proxy count for the sub-user's
// custom proxy list. The special code ZZ means any available country.
// Nil when custom proxy lists are disabled.
ProxyCountries map[string]int `json:"proxy_countries"`
// ProxyLimit is the sub-user bandwidth limit in GB. Zero means
// unlimited.
ProxyLimit float64 `json:"proxy_limit"`
// MaxThreadCount is the maximum proxy request concurrency for the
// sub-user.
MaxThreadCount int `json:"max_thread_count"`
// AggregateStats holds the proxy stats for the sub-user in the same
// shape as the aggregate stats API.
AggregateStats AggregateStats `json:"aggregate_stats"`
// CreatedAt is when the sub-user was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the sub-user was last updated.
UpdatedAt time.Time `json:"updated_at"`
// BandwidthUseStartDate is when bandwidth use calculation starts.
BandwidthUseStartDate time.Time `json:"bandwidth_use_start_date"`
// BandwidthUseEndDate is when the bandwidth use resets. Read-only.
BandwidthUseEndDate time.Time `json:"bandwidth_use_end_date"`
}
Subuser is one sub-user of the account.
type SubuserCreateParams ¶
type SubuserCreateParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
// Label identifies the sub-user.
Label string
// ProxyLimit is the bandwidth limit in GB. Zero means unlimited.
ProxyLimit *float64
// MaxThreadCount is the maximum proxy request concurrency.
MaxThreadCount *int
// ProxyCountries maps country code to proxy count for a custom proxy
// list; ZZ means any available country. Null disables custom lists.
ProxyCountries Nullable[map[string]int]
// BandwidthUseStartDate sets when bandwidth use calculation starts.
BandwidthUseStartDate *time.Time
}
SubuserCreateParams are the parameters for SubusersService.Create.
func (SubuserCreateParams) MarshalJSON ¶
func (p SubuserCreateParams) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, sending only the set fields.
type SubuserGetParams ¶
type SubuserGetParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
SubuserGetParams are the optional parameters for SubusersService.Get and Delete.
type SubuserListParams ¶
type SubuserListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
}
SubuserListParams are the parameters for SubusersService.List.
type SubuserUpdateParams ¶
type SubuserUpdateParams struct {
// PlanID targets a specific plan; otherwise the default plan is used.
PlanID *int
// Label sets the sub-user label.
Label *string
// ProxyCountries maps country code to proxy count for a custom proxy
// list; ZZ means any available country. Null disables custom lists.
ProxyCountries Nullable[map[string]int]
// ProxyLimit sets the bandwidth limit in GB. Zero means unlimited.
ProxyLimit *float64
// MaxThreadCount sets the maximum proxy request concurrency.
MaxThreadCount *int
// BandwidthUseStartDate sets when bandwidth use calculation starts.
BandwidthUseStartDate *time.Time
}
SubuserUpdateParams are the parameters for SubusersService.Update. Only set fields are sent.
func (SubuserUpdateParams) MarshalJSON ¶
func (p SubuserUpdateParams) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, sending only the set fields.
type SubusersService ¶
type SubusersService struct {
// contains filtered or unexported fields
}
SubusersService exposes the sub-user operations. The sub-user API is only available after accepting additional terms for the Webshare sub-user portal (https://proxy.webshare.io/subuser/); expect 403 responses otherwise. To act as a sub-user on the proxy config, list, stats and activity APIs, pass WithSubuser.
func (*SubusersService) Create ¶
func (s *SubusersService) Create(ctx context.Context, params SubuserCreateParams, opts ...RequestOption) (*Subuser, error)
Create creates a new sub-user.
func (*SubusersService) Delete ¶
func (s *SubusersService) Delete(ctx context.Context, id int, params SubuserGetParams, opts ...RequestOption) error
Delete removes a sub-user.
func (*SubusersService) Get ¶
func (s *SubusersService) Get(ctx context.Context, id int, params SubuserGetParams, opts ...RequestOption) (*Subuser, error)
Get retrieves a sub-user.
func (*SubusersService) List ¶
func (s *SubusersService) List(ctx context.Context, params SubuserListParams, opts ...RequestOption) (*Page[Subuser], error)
List retrieves all sub-users in paginated format.
func (*SubusersService) ListAll ¶
func (s *SubusersService) ListAll(ctx context.Context, params SubuserListParams, opts ...RequestOption) iter.Seq2[Subuser, error]
ListAll returns a lazy iterator over every sub-user across all pages.
func (*SubusersService) RefreshProxyList ¶
func (s *SubusersService) RefreshProxyList(ctx context.Context, id int, opts ...RequestOption) (*Subuser, error)
RefreshProxyList refreshes the proxy list of a sub-user. Only available when the sub-user has a custom proxy list.
func (*SubusersService) Update ¶
func (s *SubusersService) Update(ctx context.Context, id int, params SubuserUpdateParams, opts ...RequestOption) (*Subuser, error)
Update partially updates a sub-user.
type Suspension ¶
type Suspension struct {
// CreatedAt is when the account was suspended.
CreatedAt time.Time `json:"created_at"`
// Reason is the suspension reason.
Reason VerificationFlowType `json:"reason"`
}
Suspension describes when and why the account was suspended.
type TaxEntry ¶
type TaxEntry struct {
// Amount is the tax amount.
Amount string `json:"amount"`
// TaxRateDetails describes the applied tax rate.
TaxRateDetails TaxRateDetails `json:"tax_rate_details"`
// TaxableAmount is the amount the tax applies to.
TaxableAmount string `json:"taxable_amount"`
}
TaxEntry is one entry of the tax breakdown.
type TaxRateDetails ¶
type TaxRateDetails struct {
// PercentageDecimal is the tax percentage as a decimal string.
PercentageDecimal string `json:"percentage_decimal"`
// TaxType is the kind of tax, for example "gst".
TaxType string `json:"tax_type"`
}
TaxRateDetails describes an applied tax rate.
type Token ¶
type Token struct {
// Value is the secret token value.
Value string
// Scheme is the Authorization header scheme. When empty,
// DefaultAuthScheme ("Token") is used. OAuth-issued credentials may use a
// different scheme such as "Bearer".
Scheme string
}
Token is a credential presented to the API in the Authorization header as "<Scheme> <Value>".
type TokenSource ¶
type TokenSource interface {
// Token returns the credential to use for a request.
Token(ctx context.Context) (Token, error)
}
TokenSource supplies the credential used to authenticate API requests. It is called once per request, which is cheap for static keys and allows refreshing implementations (for example OAuth token sources) to always provide a current token.
func StaticTokenSource ¶
func StaticTokenSource(t Token) TokenSource
StaticTokenSource returns a TokenSource that always yields the given token.
type Transaction ¶
type Transaction struct {
// ID is the unique identifier of the transaction instance.
ID int `json:"id"`
// Status is the transaction status. Partial refunds show as refunded.
Status TransactionStatus `json:"status"`
// PaymentMethod is the nested payment method used for the transaction.
PaymentMethod PaymentMethod `json:"payment_method"`
// Reason describes the transaction.
Reason string `json:"reason"`
// Amount is the transaction amount in USD.
Amount float64 `json:"amount"`
// CreditsUsed is the credits used in the transaction.
CreditsUsed float64 `json:"credits_used"`
// CreditsGained is the credits gained in the transaction (for example
// when downgrading).
CreditsGained float64 `json:"credits_gained"`
// RefundAmount is the amount refunded in USD.
RefundAmount float64 `json:"refund_amount"`
// RefundDate is when the last refund was issued. May be nil.
RefundDate *time.Time `json:"refund_date"`
// LineItems carries the transaction line items. Observed on the live
// API (as null) and absent from the documented object; its shape is
// undocumented, so the raw JSON is preserved.
LineItems json.RawMessage `json:"line_items,omitempty"`
// CreatedAt is when this instance was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
Transaction is a completed payment transaction.
type TransactionListParams ¶
type TransactionListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
TransactionListParams are the parameters for TransactionsService.List.
type TransactionStatus ¶
type TransactionStatus string
TransactionStatus is the status of a transaction. There is no failed state: failed payments live on PendingPayment.
const ( // TransactionCompleted means the transaction completed. TransactionCompleted TransactionStatus = "completed" // TransactionRefunded means the transaction was (partially) refunded. TransactionRefunded TransactionStatus = "refunded" )
Transaction statuses.
type TransactionsService ¶
type TransactionsService struct {
// contains filtered or unexported fields
}
TransactionsService exposes the transaction operations.
func (*TransactionsService) Get ¶
func (s *TransactionsService) Get(ctx context.Context, id int, opts ...RequestOption) (*Transaction, error)
Get retrieves a transaction.
func (*TransactionsService) List ¶
func (s *TransactionsService) List(ctx context.Context, params TransactionListParams, opts ...RequestOption) (*Page[Transaction], error)
List retrieves the transactions in paginated format.
func (*TransactionsService) ListAll ¶
func (s *TransactionsService) ListAll(ctx context.Context, params TransactionListParams, opts ...RequestOption) iter.Seq2[Transaction, error]
ListAll returns a lazy iterator over every transaction across all pages.
type VerificationAbuseReportsService ¶
type VerificationAbuseReportsService struct {
// contains filtered or unexported fields
}
VerificationAbuseReportsService exposes the abuse report operations.
func (*VerificationAbuseReportsService) List ¶
func (s *VerificationAbuseReportsService) List(ctx context.Context, params AbuseReportListParams, opts ...RequestOption) (*Page[AbuseReport], error)
List returns the abuse reports raised against the account in paginated format.
func (*VerificationAbuseReportsService) ListAll ¶
func (s *VerificationAbuseReportsService) ListAll(ctx context.Context, params AbuseReportListParams, opts ...RequestOption) iter.Seq2[AbuseReport, error]
ListAll returns a lazy iterator over every abuse report across all pages.
type VerificationAnswer ¶
type VerificationAnswer struct {
// ID is the unique identifier of the answer.
ID int `json:"id"`
// Answer is the answer text.
Answer string `json:"answer"`
// CreatedAt is when the answer was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the answer was last updated.
UpdatedAt time.Time `json:"updated_at"`
// Files lists the attachments submitted with the answer.
Files []VerificationFile `json:"files"`
}
VerificationAnswer is the answer submitted for a verification question.
type VerificationAppeal ¶
type VerificationAppeal struct {
// ID is the unique identifier of the appeal.
ID int `json:"id"`
// Appeal is the appeal text.
Appeal string `json:"appeal"`
// State is the appeal state.
State AppealState `json:"state"`
// CreatedAt is when the appeal was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the appeal was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
VerificationAppeal is a suspension appeal.
type VerificationAppealCreateParams ¶
type VerificationAppealCreateParams struct {
// Appeal is the appeal text to submit for the account suspension.
Appeal string `json:"appeal"`
}
VerificationAppealCreateParams are the parameters for VerificationAppealsService.Create.
type VerificationAppealListParams ¶
type VerificationAppealListParams struct {
// State matches only appeals in the given state.
State AppealState
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
VerificationAppealListParams are the parameters for VerificationAppealsService.List.
type VerificationAppealsService ¶
type VerificationAppealsService struct {
// contains filtered or unexported fields
}
VerificationAppealsService exposes the suspension appeal operations.
func (*VerificationAppealsService) Create ¶
func (s *VerificationAppealsService) Create(ctx context.Context, params VerificationAppealCreateParams, opts ...RequestOption) (*VerificationAppeal, error)
Create submits an appeal for an account suspension. Only one appeal can be submitted at a time.
func (*VerificationAppealsService) List ¶
func (s *VerificationAppealsService) List(ctx context.Context, params VerificationAppealListParams, opts ...RequestOption) (*Page[VerificationAppeal], error)
List returns the appeals submitted for the account in paginated format.
func (*VerificationAppealsService) ListAll ¶
func (s *VerificationAppealsService) ListAll(ctx context.Context, params VerificationAppealListParams, opts ...RequestOption) iter.Seq2[VerificationAppeal, error]
ListAll returns a lazy iterator over every appeal across all pages.
type VerificationCategory ¶
type VerificationCategory struct {
// Description describes the category. Can be user visible.
Description string `json:"description"`
// RequestThreshold previously held the triggering request threshold;
// it is now always nil.
RequestThreshold *int `json:"request_threshold"`
// IDVerificationRequired reports whether the category requires ID
// verification when triggered.
IDVerificationRequired bool `json:"id_verification_required"`
// IDVerificationRestoresAccess reports whether completing ID
// verification restores proxy access.
IDVerificationRestoresAccess bool `json:"id_verification_restores_access"`
}
VerificationCategory describes one verification category.
type VerificationEvidence ¶
type VerificationEvidence struct {
// ID is the unique identifier of the evidence.
ID int `json:"id"`
// Explanation is the explanation submitted with the evidence.
Explanation string `json:"explanation"`
// CreatedAt is when the evidence was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the evidence was last updated.
UpdatedAt time.Time `json:"updated_at"`
// Files lists the submitted files.
Files []VerificationFile `json:"files"`
}
VerificationEvidence is the evidence submitted for a verification flow.
type VerificationFile ¶
type VerificationFile struct {
// ID is the unique identifier of the file.
ID int `json:"id"`
// File is the stored file reference.
File string `json:"file"`
// CreatedAt is when the file was uploaded.
CreatedAt time.Time `json:"created_at"`
}
VerificationFile is a file attached to evidence or an answer.
type VerificationFlow ¶
type VerificationFlow struct {
// ID is the unique identifier of the verification instance.
ID int `json:"id"`
// Type is the verification type.
Type VerificationFlowType `json:"type"`
// State is the current state of the verification.
State VerificationFlowState `json:"state"`
// StartedAt is when this verification started.
StartedAt time.Time `json:"started_at"`
// UpdatedAt is when this instance was last updated.
UpdatedAt time.Time `json:"updated_at"`
// NeedsEvidence reports whether the verification requires evidence.
NeedsEvidence bool `json:"needs_evidence"`
// Evidence holds the submitted evidence. May be nil.
Evidence *VerificationEvidence `json:"evidence"`
// IDVerificationRestoresAccess reports whether completing ID
// verification restores proxy access.
IDVerificationRestoresAccess bool `json:"id_verification_restores_access"`
// IDVerificationRequired reports whether this verification requires ID
// verification.
IDVerificationRequired bool `json:"id_verification_required"`
}
VerificationFlow is one account verification.
type VerificationFlowListParams ¶
type VerificationFlowListParams struct {
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
VerificationFlowListParams are the parameters for VerificationFlowsService.List.
type VerificationFlowState ¶
type VerificationFlowState string
VerificationFlowState is the state of a verification flow.
const ( // FlowInflow means the verification is in progress. FlowInflow VerificationFlowState = "inflow" // FlowSuccessful means the verification succeeded. FlowSuccessful VerificationFlowState = "successful_verification" // FlowFailed means the verification failed. FlowFailed VerificationFlowState = "failed_verification" )
Verification flow states.
type VerificationFlowType ¶
type VerificationFlowType string
VerificationFlowType is the kind of verification flow.
const ( // FlowAcceptableUseViolation is a verification for acceptable use // policy violations. FlowAcceptableUseViolation VerificationFlowType = "acceptable_use_violation" // FlowAbuseReport is a verification for abuse reports. FlowAbuseReport VerificationFlowType = "abuse_report" // FlowFraudulentPayment is a verification for fraudulent payments. FlowFraudulentPayment VerificationFlowType = "fraudulent_payment" )
Verification flow types.
type VerificationFlowsService ¶
type VerificationFlowsService struct {
// contains filtered or unexported fields
}
VerificationFlowsService exposes the verification flow operations.
func (*VerificationFlowsService) Get ¶
func (s *VerificationFlowsService) Get(ctx context.Context, id int, opts ...RequestOption) (*VerificationFlow, error)
Get retrieves an account verification.
func (*VerificationFlowsService) List ¶
func (s *VerificationFlowsService) List(ctx context.Context, params VerificationFlowListParams, opts ...RequestOption) (*Page[VerificationFlow], error)
List returns the account verifications in paginated format.
func (*VerificationFlowsService) ListAll ¶
func (s *VerificationFlowsService) ListAll(ctx context.Context, params VerificationFlowListParams, opts ...RequestOption) iter.Seq2[VerificationFlow, error]
ListAll returns a lazy iterator over every verification flow across all pages.
func (*VerificationFlowsService) SubmitEvidence ¶
func (s *VerificationFlowsService) SubmitEvidence(ctx context.Context, id int, params SubmitEvidenceParams, opts ...RequestOption) (*VerificationFlow, error)
SubmitEvidence submits evidence for a verification. At least one of Explanation and Files must be set. The request is encoded as multipart/form-data.
func (*VerificationFlowsService) SubmitSecurityCode ¶
func (s *VerificationFlowsService) SubmitSecurityCode(ctx context.Context, id int, params SubmitSecurityCodeParams, opts ...RequestOption) (*VerificationFlow, error)
SubmitSecurityCode submits a security code for a fraudulent payment verification flow.
type VerificationLimits ¶
type VerificationLimits struct {
// ProxyState is the current proxy limit state.
ProxyState ProxyState `json:"proxy_state"`
}
VerificationLimits describes limits the account may have received.
type VerificationQuestion ¶
type VerificationQuestion struct {
// ID is the unique identifier of the question.
ID int `json:"id"`
// Question is the question text.
Question string `json:"question"`
// CreatedAt is when the question was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the question was last updated.
UpdatedAt time.Time `json:"updated_at"`
// Flow is the ID of the related verification flow.
Flow int `json:"flow"`
// Answer holds the submitted answer, or nil when unanswered.
Answer *VerificationAnswer `json:"answer"`
}
VerificationQuestion is a question submitted by the compliance team.
type VerificationQuestionListParams ¶
type VerificationQuestionListParams struct {
// FlowType matches questions whose verification flow has the given
// type.
FlowType VerificationFlowType
// FlowState matches questions whose verification flow is in the given
// state.
FlowState VerificationFlowState
// AnswerIsNull set to true shows only unanswered questions; false shows
// only answered ones.
AnswerIsNull *bool
// FlowStartedAtGTE bounds the flow start date from below.
FlowStartedAtGTE *time.Time
// FlowStartedAtLTE bounds the flow start date from above.
FlowStartedAtLTE *time.Time
// Question matches questions with the given question text.
Question string
// AnswerAnswer matches questions with the given answer text.
AnswerAnswer string
// Page is the page number.
Page *int
// PageSize is the number of results per page.
PageSize *int
}
VerificationQuestionListParams are the parameters for VerificationQuestionsService.List.
type VerificationQuestionsService ¶
type VerificationQuestionsService struct {
// contains filtered or unexported fields
}
VerificationQuestionsService exposes the verification question operations.
func (*VerificationQuestionsService) List ¶
func (s *VerificationQuestionsService) List(ctx context.Context, params VerificationQuestionListParams, opts ...RequestOption) (*Page[VerificationQuestion], error)
List returns the compliance questions in paginated format.
func (*VerificationQuestionsService) ListAll ¶
func (s *VerificationQuestionsService) ListAll(ctx context.Context, params VerificationQuestionListParams, opts ...RequestOption) iter.Seq2[VerificationQuestion, error]
ListAll returns a lazy iterator over every verification question across all pages.
func (*VerificationQuestionsService) SubmitAnswer ¶
func (s *VerificationQuestionsService) SubmitAnswer(ctx context.Context, questionID int, params SubmitAnswerParams, opts ...RequestOption) (*VerificationAnswer, error)
SubmitAnswer submits an answer for a verification question with optional attachments. At least one of Answer and Files must be set. The request is encoded as multipart/form-data.
type VerificationService ¶
type VerificationService struct {
// Flows exposes the verification flow operations.
Flows *VerificationFlowsService
// Questions exposes the verification question operations.
Questions *VerificationQuestionsService
// Appeals exposes the suspension appeal operations.
Appeals *VerificationAppealsService
// AbuseReports exposes the abuse report operations.
AbuseReports *VerificationAbuseReportsService
// contains filtered or unexported fields
}
VerificationService exposes the account verification (compliance) operations, grouped into nested subresources.
func (*VerificationService) GetCategories ¶
func (s *VerificationService) GetCategories(ctx context.Context, opts ...RequestOption) (map[string]VerificationCategory, error)
GetCategories retrieves the verification categories that may trigger verification flows. The response is a map keyed by category name.
func (*VerificationService) GetLimits ¶
func (s *VerificationService) GetLimits(ctx context.Context, opts ...RequestOption) (*VerificationLimits, error)
GetLimits retrieves the verification limits applied to the account.
func (*VerificationService) GetSuspension ¶
func (s *VerificationService) GetSuspension(ctx context.Context, opts ...RequestOption) (*Suspension, error)
GetSuspension returns when the account was suspended and why. This endpoint works even while the account is suspended.
func (*VerificationService) GetThresholds ¶
func (s *VerificationService) GetThresholds(ctx context.Context, opts ...RequestOption) (map[string]VerificationThreshold, error)
GetThresholds retrieves the thresholds that may trigger an acceptable use verification flow. The response is a map keyed by category name.
type VerificationThreshold ¶
type VerificationThreshold struct {
// Description describes the trigger. Can be user visible.
Description string `json:"description"`
// IDVerificationRequired reports whether the threshold requires ID
// verification when triggered.
IDVerificationRequired bool `json:"id_verification_required"`
// IDVerificationRestoresAccess reports whether completing ID
// verification restores proxy access.
IDVerificationRestoresAccess bool `json:"id_verification_restores_access"`
// RequestCount is the number of proxy requests matching this trigger.
RequestCount int `json:"request_count"`
// RequestThreshold previously held the triggering request count; it is
// now always nil.
RequestThreshold *int `json:"request_threshold"`
// Triggered reports whether the threshold has been triggered.
Triggered bool `json:"triggered"`
}
VerificationThreshold describes one verification trigger threshold.
type WhatsMyIPResult ¶
type WhatsMyIPResult struct {
// IPAddress is the caller's public IP address.
IPAddress string `json:"ip_address"`
}
WhatsMyIPResult is the response of IPAuthorizationsService.WhatsMyIP.
Source Files
¶
- billing.go
- client.go
- credentials.go
- downloadtokens.go
- errors.go
- idverification.go
- invoices.go
- ipauthorizations.go
- notifications.go
- options.go
- pagination.go
- paymentmethods.go
- pendingpayments.go
- plans.go
- profile.go
- proxies.go
- proxyactivity.go
- proxyconfig.go
- proxyreplacements.go
- proxyurl.go
- referral.go
- replacedproxies.go
- request.go
- stats.go
- subscription.go
- subusers.go
- transactions.go
- types.go
- verification.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
downloadproxylist
command
Command downloadproxylist fetches the proxy list download token from the proxy config API and downloads the proxy list as plain text.
|
Command downloadproxylist fetches the proxy list download token from the proxy config API and downloads the proxy list as plain text. |
|
errorhandling
command
Command errorhandling demonstrates how to inspect API and transport errors returned by the SDK.
|
Command errorhandling demonstrates how to inspect API and transport errors returned by the SDK. |
|
listproxies
command
Command listproxies lists the first page of a plan's proxies, then iterates the entire proxy list using automatic pagination.
|
Command listproxies lists the first page of a plan's proxies, then iterates the entire proxy list using automatic pagination. |
|
plans
command
Command plans lists the account's proxy plans, selects one, and uses its ID across plan-scoped calls: the proxy list, the proxy configuration and the proxy list download URL.
|
Command plans lists the account's proxy plans, selects one, and uses its ID across plan-scoped calls: the proxy list, the proxy configuration and the proxy list download URL. |
|
proxyconnection
command
Command proxyconnection builds proxy connection URLs with the ProxyURL helper and uses one to configure an *http.Client.
|
Command proxyconnection builds proxy connection URLs with the ProxyURL helper and uses one to configure an *http.Client. |