Libraries
Go SDK
In short
Run go get github.com/rocketverifier/sdk-go, create a client with rocketverifier.New(apiKey) and call rv.Verify(ctx, email, nil). The module uses only the standard library, takes a context on every call, retries safely with a stable Idempotency-Key and returns typed errors you match with errors.Is.
On this page
- Install the SDK
- Create a client
- Verify an email
- Result fields
- Verify a list in bulk
- Read results
- Download results
- Upload a file
- Check a domain, credits and account
- Manage monitors
- Manage webhook endpoints
- Verify webhook signatures
- Act for a user with OAuth
- Handle errors
- Retries and timeouts
- Next steps
- Frequently asked questions
github.com/rocketverifier/sdk-go is the official Go client for the RocketVerifier API. It covers real-time verification, bulk jobs from a list or a file, progress and downloads, webhooks, monitors, credits and RocketVerifier Connect OAuth, with no dependencies outside the standard library.
- Module
- github.com/rocketverifier/sdk-go
- Version
- 1.0.0
- Go
- 1.21+
- Dependencies
- None
Install the SDK#
Add the module to your project. The package name is rocketverifier.
go get github.com/rocketverifier/sdk-goimport rocketverifier "github.com/rocketverifier/sdk-go"Create a client#
rocketverifier.New(apiKey, opts...) returns a *Client that is safe for concurrent use. Read the key from ROCKETVERIFIER_API_KEY so it never lands in source control.
rv, err := rocketverifier.New(
os.Getenv("ROCKETVERIFIER_API_KEY"),
rocketverifier.WithTimeout(15*time.Second),
rocketverifier.WithMaxRetries(5),
)
if err != nil {
log.Fatal(err)
}New returns an error when the key is empty. Live keys start with rv_live_; sandbox keys start with rv_test_ and accept only sandbox addresses. See authentication.
| Option | Default | What it does |
|---|---|---|
WithBaseURL(url) | https://api.rocketverifier.com | API base URL. |
WithTimeout(d) | 30 * time.Second | Timeout per attempt. Each retry gets the full timeout again. |
WithMaxRetries(n) | 3 | Retries on 429, timeouts and network errors. 0 turns retries off. |
WithHTTPClient(hc) | &http.Client{} | Your own *http.Client, for proxies or tracing. |
WithHeader(key, value) | none | Extra header on every request, applied last. |
WithRefreshToken(token) | none | OAuth refresh token for automatic refresh. |
WithOAuth(o) | none | The *OAuth helper used for automatic refresh. |
WithTokenRefreshHandler(fn) | none | Called with the new *TokenSet after a refresh. Persist it here. |
Verify an email#
rv.Verify(ctx, email, opts) checks one address with POST /v1/verify and returns a *VerificationResult. Branch on Status and read SubStatus for the reason.
ctx := context.Background()
result, err := rv.Verify(ctx, "deliverable@sandbox.rocketverifier.com", nil)
if err != nil {
log.Fatal(err)
}
switch result.Status {
case rocketverifier.StatusDeliverable:
// send
case rocketverifier.StatusRisky:
fmt.Println("review:", result.SubStatus)
case rocketverifier.StatusUndeliverable:
if result.DidYouMean != nil {
fmt.Println("did you mean", *result.DidYouMean)
}
case rocketverifier.StatusUnknown:
// free: check again later
}VerifyOptions has IdempotencyKey (a random key is used when empty) and Timeout, the server side verification timeout in seconds. The SDK accepts 5 to 60 and grows the HTTP timeout to cover it. Input without an @ returns a validation error before any request is sent. The reading results guide explains every status and sub_status.
Result fields#
| Field | Type | API field |
|---|---|---|
Email, Status, Reason | string | email, status, reason |
SubStatus | string | sub_status, "none" when not specific |
Score | float64 | score, 0 to 100 |
CatchAllVerdict | *string | catch_all_verdict |
DidYouMean | *string | did_you_mean |
VerifiedAt | *string | verified_at |
Provider | *string | provider |
Domain | DomainInfo | Name, AcceptAll *bool, Disposable bool, Free bool, AcceptAllConfidence, AcceptAllVerdict |
Account | *AccountInfo | Role bool, Disabled *bool, FullMailbox *bool |
DNS | *DNSInfo | Type, Record |
AuthenticationScore | *float64 | authentication_score |
DeliverabilityTier | *string | deliverability_tier |
Toxic, Abuse | *string | "yes", "no" or "unknown" |
SpamTrap | bool | spam_trap |
Activity, Evidence | map[string]any | activity, evidence |
Raw | json.RawMessage | The full response body |
IsDeliverable(), IsUndeliverable(), IsRisky() and IsUnknown() test the status. The "yes", "no" and "unknown" flags become Go booleans: plain bool fields are true only for "yes", and *bool fields are nil when the server reports "unknown". Read any other field from Raw.
Verify a list in bulk#
rv.Batch runs bulk jobs of up to 100,000 unique addresses. The batch API reference covers the endpoints.
job, err := rv.Batch.Create(ctx, &rocketverifier.BatchCreateParams{
Name: "October signups",
Emails: []string{"deliverable@sandbox.rocketverifier.com", "undeliverable@sandbox.rocketverifier.com"},
})
if err != nil {
log.Fatal(err)
}
done, err := rv.Batch.Wait(ctx, job.JobID, &rocketverifier.WaitOptions{
PollInterval: 3 * time.Second,
OnProgress: func(j *rocketverifier.BatchJob) {
fmt.Printf("%d/%d\n", j.ProcessedEmails, j.TotalEmails)
},
})- Create:
Batch.Create(ctx, *BatchCreateParams{Emails, Name, IdempotencyKey})returnsJobID,TotalEmails,EstimatedTimeSeconds,CreditsToUseandCreditsRemaining. The limit applies to unique addresses. - Wait:
Batch.Wait(ctx, jobID, *WaitOptions)polls everyPollInterval(5 seconds) until the job is completed, failed or cancelled, or reachesawaiting_confirmation. PastTimeout(5 minutes) it returns an error withKind == KindTimeout, and it stops early whenctxis done. - Get:
Batch.Get(ctx, jobID)returns a*BatchJobwith counts,ProgressPercentand timestamps.IsFinished()andIsAwaitingConfirmation()test the status. - Progress:
Batch.Progress(ctx, jobID)returns a*JobProgresswithTotal,Processed,Remaining,Percent,Counts,CountsByStatus,RatePerMinuteandETASeconds. - List:
Batch.List(ctx, *ListOptions{Page, Limit, Status})returns a*JobsPage.Limitdefaults to 20, up to 100. - Cancel:
Batch.Delete(ctx, jobID)orBatch.Cancel(ctx, jobID)returnsRefundedCreditsfor unprocessed addresses.
Read results#
Batch.Results returns one page, Batch.Iterate walks every row and Batch.AllResults returns them all in one slice.
it := rv.Batch.Iterate(ctx, jobID, &rocketverifier.ResultsOptions{Classification: "valid"})
for it.Next() {
r := it.Result()
fmt.Println(r.Email, r.SubStatus)
}
if err := it.Err(); err != nil {
log.Fatal(err)
}ResultsOptions has Page, Limit (100 for Results, 1000 for Iterate and AllResults, up to 1000) and Classification. Each JobResult has Email, Classification, IsValid, IsDisposable, IsCatchAll, IsRoleBased, ConfidenceScore, SubStatus and VerifiedAt.
Download results#
Three methods download the full results of a completed job. DownloadOptions has Format, Filter (deliverable, undeliverable, risky, unknown or send_safe) and IncludeOriginal.
csv, err := rv.Batch.Download(ctx, jobID, nil) // raw CSV bytes
rows, err := rv.Batch.DownloadRows(ctx, jobID, &rocketverifier.DownloadOptions{Filter: "send_safe"})
data, err := rv.Batch.DownloadJSON(ctx, jobID, nil) // JobID, ResultsDownloadRows parses the CSV with ParseDownloadCSV: boolean columns become bool and score columns become numbers.
Upload a file#
Batch.Upload(ctx, *UploadParams) creates a job from a CSV, TSV, TXT or XLSX file of up to 50 MB, or from a public HTTPS URL. Set exactly one of File, FilePath or SourceURL. See bulk upload.
up, err := rv.Batch.Upload(ctx, &rocketverifier.UploadParams{
FilePath: "contacts.csv",
EmailColumn: "Work Email",
Preview: true,
})
if err != nil {
log.Fatal(err)
}
preview, err := rv.Batch.Preview(ctx, up.JobID, false)
for err == nil && preview.Pending {
time.Sleep(2 * time.Second)
preview, err = rv.Batch.Preview(ctx, up.JobID, false)
}
fmt.Println(preview.Preview["estimated_bounce_rate"])
confirmed, err := rv.Batch.Confirm(ctx, up.JobID, "")UploadParamsalso takesFile(anio.Reader) withFilename,Name,ColumnMapping,CallbackURL,ContentTypeandIdempotencyKey.EmailColumnis a header name or a 0-based index.BatchUploadResulthasJobID,Status,Preview,StatusURL,ProgressURLandCallbackSecret, which is set once when you passCallbackURL.Batch.Preview(ctx, jobID, refresh)returns the free list health estimate as a map, withPendingset while it is computing.Batch.Confirm(ctx, jobID, idempotencyKey)charges and starts the job. A job is never charged twice, so it is safe to retry.
Check a domain, credits and account#
info, err := rv.Domain.Check(ctx, "northwind.io") // Domain, MXRecords, Provider, Disposable, HasValidMX
credits, err := rv.Credits(ctx) // Credits, UsedToday, UsedThisMonth
me, err := rv.Me(ctx) // Email, AccountType, Organization, Credits, AuthType, Scopes, AppMe calls GET /v1/me. me.IsOAuth() is true for OAuth tokens.
Manage monitors#
rv.Monitors schedules list health re-verification and SPF, DKIM and DMARC checks. See the monitors API.
m, err := rv.Monitors.Create(ctx, &rocketverifier.MonitorCreateParams{
Name: "Brand domain",
Type: rocketverifier.MonitorTypeDomainAuth,
Domain: "northwind.io",
})| Method | What it does |
|---|---|
Create(ctx, *MonitorCreateParams) | Frequency defaults to weekly, AlertThreshold to 5. domain_auth needs Domain; list_health needs Emails. |
List(ctx), Get(ctx, id) | Return Monitor values. |
Update(ctx, id, *MonitorUpdateParams) | Pointer fields left nil are unchanged. |
Delete(ctx, id) | Removes the monitor. |
Runs(ctx, id, *PageOptions) | A *MonitorRunsPage, most recent first. |
RunNow(ctx, id, idempotencyKey) | Runs it immediately. list_health runs cost 1 credit per address. |
Manage webhook endpoints#
rv.Webhooks registers HTTPS endpoints for events such as job.completed. It needs the webhooks:manage scope. See the webhooks API.
hook, err := rv.Webhooks.Create(ctx, &rocketverifier.WebhookCreateParams{
URL: "https://northwind.io/hooks/rocketverifier",
Events: []string{rocketverifier.EventJobCompleted, rocketverifier.EventJobFailed},
})
// Store hook.Secret now: it is shown only once.The service also has ListEvents, List, Get, Update (with *WebhookUpdateParams), Delete, Test, Logs (with *WebhookLogsOptions{Page, Limit, Status}) and RotateSecret. Event names are exported as EventJobCompleted, EventJobFailed, EventCreditsLow, EventCreditsDepleted, EventEmailVerified and EventMonitorAlert.
Verify webhook signatures#
ConstructEvent checks the X-RocketVerifier-Signature header and the timestamp, then returns the event. Pass the raw body exactly as received.
http.HandleFunc("/hooks/rocketverifier", func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
header := strings.Join(r.Header.Values(rocketverifier.SignatureHeader), ",")
event, err := rocketverifier.ConstructEvent(body, header, os.Getenv("ROCKETVERIFIER_WEBHOOK_SECRET"))
if err != nil {
http.Error(w, "invalid signature", http.StatusBadRequest)
return
}
if event.Event == rocketverifier.EventJobCompleted {
var data struct {
JobID string `json:"job_id"`
}
_ = event.DecodeData(&data)
log.Printf("job %s finished", data.JobID)
}
w.WriteHeader(http.StatusOK)
})VerifySignature(rawBody, header, secret, opts...)returnsnilor a*WebhookSignatureErrorwhoseReasonismissing_secret,missing_header,malformed_header,timestamp_out_of_toleranceorsignature_mismatch.ConstructEventaddsinvalid_json.WithTolerance(d)changes the 300 second window;WithNow(t)fixes the clock in tests.GenerateSignatureHeader(rawBody, secret, timestamp)builds a valid header for testing your endpoint.
Act for a user with OAuth#
NewOAuth runs the RocketVerifier Connect authorization code flow with PKCE; NewWithAccessToken calls the API for the connected user. The OAuth guide covers app registration.
oauth, err := rocketverifier.NewOAuth(rocketverifier.OAuthConfig{
ClientID: os.Getenv("RV_CLIENT_ID"),
ClientSecret: os.Getenv("RV_CLIENT_SECRET"),
RedirectURI: "https://northwind.io/rocketverifier/callback",
})
auth, err := oauth.AuthorizeURL(rocketverifier.AuthorizeParams{Scopes: []string{"verify:bulk", "account:read"}})
// store auth.State and auth.CodeVerifier, redirect to auth.URL
tokens, err := oauth.ExchangeCode(ctx, code, auth.CodeVerifier, "")
userRV, err := rocketverifier.NewWithAccessToken(tokens.AccessToken,
rocketverifier.WithRefreshToken(tokens.RefreshToken),
rocketverifier.WithOAuth(oauth),
rocketverifier.WithTokenRefreshHandler(func(ctx context.Context, t *rocketverifier.TokenSet) error {
return saveTokens(ctx, userID, t)
}),
)OAuthConfigalso takesIssuer(defaulthttps://app.rocketverifier.com),TokenEndpointAuthMethod(defaultclient_secret_basic),HTTPClientandTimeout. LeaveClientSecretempty for public clients.OAuthhasAuthorizeURL,ExchangeCode,Refresh,RevokeandIntrospect.TokenSetholdsAccessToken,RefreshToken,TokenType,ExpiresIn,ExpiresAt(time.Time) andScopes.- On a 401
invalid_tokenthe client refreshes once, retries and calls your handler. Without refresh configured, it returns an error matchingErrInvalidToken. A rejected refresh token returns an*OAuthErrorwithErrorCode == "invalid_grant". rv.SetTokens(accessToken, refreshToken)swaps in tokens refreshed elsewhere.
Handle errors#
Every API failure is a *rocketverifier.Error with Kind, Code, StatusCode, Message, Details, RetryAfter and Err. Match it with errors.Is and the sentinel errors.
| Sentinel | Kind | Returned when |
|---|---|---|
ErrAuthentication | KindAuthentication | 401. Also matches invalid token errors. |
ErrInvalidToken | KindInvalidToken | 401 invalid_token for an OAuth token that cannot be refreshed. |
ErrInsufficientCredits | KindInsufficientCredits | 402, or code insufficient_credits (including the 403 at zero balance). |
ErrRateLimited | KindRateLimit | 429 after all retries. RetryAfter holds the seconds. |
ErrValidation | KindValidation | 400 or 422, or input rejected before sending. |
ErrPermissionDenied | KindPermissionDenied | 403, such as a missing scope. |
ErrNotFound | KindNotFound | 404. |
ErrTimeout | KindTimeout | The request or Batch.Wait timed out. StatusCode is 408. |
ErrNetwork | KindNetwork | The connection failed. StatusCode is 0. |
_, err := rv.Verify(ctx, "maya@northwind.io", nil)
var apiErr *rocketverifier.Error
switch {
case errors.Is(err, rocketverifier.ErrInsufficientCredits):
// top up
case errors.As(err, &apiErr) && apiErr.Kind == rocketverifier.KindRateLimit:
time.Sleep(time.Duration(apiErr.RetryAfter) * time.Second)
case err != nil:
log.Fatal(err)
}The errors reference lists every API error code.
Retries and timeouts#
- Rate limits (429): retried up to
WithMaxRetriestimes, waiting for theRetry-Afterseconds, or 60 seconds when the header is missing. See rate limits. - Timeouts and network errors: retried with 1, 2 and 3 second waits.
- Other errors: returned straight away.
- Context: a cancelled or expired
ctxstops the call and any wait between retries. - Idempotency: every POST, PUT and PATCH sends an
Idempotency-Keyreused across retries of that call.
Next steps#
Frequently asked questions
Does the Go SDK have dependencies?
No. It uses only the Go standard library and needs Go 1.21 or later.
Is the client safe for concurrent use?
Yes. Create one *rocketverifier.Client and share it across goroutines. OAuth refresh is serialized, so concurrent calls share a single refresh.
How do I check for a specific error?
Use errors.Is(err, rocketverifier.ErrInsufficientCredits) and the other sentinel errors, or errors.As into *rocketverifier.Error to read Code, StatusCode and RetryAfter.
Which errors does the SDK retry?
Rate limits (429), timeouts and network errors, up to WithMaxRetries times (3 by default). Other 4xx and 5xx responses are returned straight away.
Updated 11 November 2026Suggest an edit