Documentation
ΒΆ
Overview ΒΆ
Package neverbounce is a small, typed, standard-library-only Go client for the NeverBounce API v4.2 (https://api.neverbounce.com/v4.2): single-email verification and the bulk-jobs workflow.
Create one Client with NewClient and your v4 API key, share it, and call one method per operation. Every method takes a context and a request struct. Each operation method makes exactly one HTTP attempt; the two helpers make one per poll or page, within a budget you set.
client, err := neverbounce.NewClient(apiKey)
if err != nil {
return err
}
res, err := client.CheckEmail(ctx, neverbounce.CheckEmailRequest{Email: "avery.example@example.com"})
if err != nil {
return err // the check may already be billed: never resend blindly
}
if res.Result == neverbounce.ResultUnknown {
// a successful answer, not an error
}
Operations and billing ΒΆ
Nothing paid or state-changing happens unless you call the method that does it:
Method Operation Effect CheckEmail single/check PAID: 1 credit per call, duplicates and bad syntax included CreateJob jobs/create creates a durable job; PAID when AutoStart is true ParseJob jobs/parse parses a job once; PAID when AutoStart is true StartJob jobs/start PAID and irreversible, unless RunSample (free) JobStatus jobs/status free, read-only JobResults jobs/results free, read-only, one page DownloadJob jobs/download free, read-only, streams the CSV to your writer WaitForJob jobs/status free: polls status only, within MaxWait JobResultPages jobs/results free: an iterator, one call per page, within MaxPages
The provider documents no sandbox and no free test addresses. The SDK never retries, hedges, follows a redirect, paginates on its own, or creates, parses, starts, polls or resubmits a job you did not ask for, and it disables the standard library's automatic resends. After a timeout, a cancellation, a transport failure or an unreadable response, the provider may already have billed the check or created or started the job: inspect before repeating. Requests that fail local validation, and calls whose context is already done, send nothing.
Verifying a list ΒΆ
The deliberate flow creates a job that only parses, waits for it, inspects the provider's billable count, and starts it explicitly:
created, err := client.CreateJob(ctx, neverbounce.CreateJobRequest{
Supplied: neverbounce.EmailList(addresses...),
Filename: "signups-2026-10-15-a7f3", // unique: findable after an ambiguous create
AutoParse: true, // AutoStart stays false: nothing billed yet
})
if err != nil {
return err // a job may exist anyway: look for its Filename before resubmitting
}
st, err := client.WaitForJob(ctx, neverbounce.WaitForJobRequest{JobID: created.JobID, MaxWait: 15 * time.Minute})
if err != nil {
return err
}
if st.State != neverbounce.JobStateWaiting || st.Totals.Billable == nil || *st.Totals.Billable > budget {
return errOverBudget // Totals.Billable is what a full start costs
}
_, err = client.StartJob(ctx, neverbounce.StartJobRequest{JobID: created.JobID}) // PAID and irreversible
Then read the results a page at a time with JobResults or JobResultPages, or stream the CSV with DownloadJob. Correlate rows by a column of your own, never by position: the provider may return a list's header row as a record.
The provider's usage guidelines, which the SDK documents and never enforces: never verify an existing list one address at a time with CheckEmail; run at most 10 concurrent jobs and 50 runs a day; create no more than 10 jobs per 100,000 items per hour; keep a supplied list within 25 MB (MaxJobRequestBytes); split millions of addresses into chunks of 1 million; and poll every 5 to 10 seconds for lists under 50,000 addresses, less often for larger ones.
Errors ΒΆ
Validation failures are *ValidationError values matching ErrInvalidConfig or ErrInvalidRequest: nothing was sent. Every other failure is a *CallError, whose Kind matches one sentinel (or context.Canceled or context.DeadlineExceeded) with errors.Is, and whose Op, StatusCode, APIStatus, JobID, Page, Field and BytesWritten say where it happened. The provider reports most errors inside an HTTP 200 envelope: its status decides the kind (auth_failure and bad_referrer are ErrUnauthorized, throttle_triggered ErrRateLimited, temp_unavail ErrUnavailable and general_failure ErrRejected). Any other HTTP status decides on its own. ErrTimeout also matches context.DeadlineExceeded, so check it first.
Error strings hold only the operation, the kind, the HTTP and API statuses and a JSON field path: never the API key, email addresses, row data, URLs, header values, response bodies or provider messages. The provider's message is kept only with WithProviderDiagnostics, behind (*CallError).Diagnostics, with the key scrubbed.
Personal data ΒΆ
Requests and results hold contact data. The SDK never logs, prints, stores or caches anything, and never reads credentials or configuration from the environment, but its result types have no redacting formatter: access control, logging, retention, security and lawful use are the caller's responsibility, and hashing an address does not anonymize it. A verification result is the provider's observation: it does not establish consent, identity, ownership or future deliverability. RemoteURL, CallbackURL and CallbackHeaders may carry third-party credentials; CreateJobRequest's String, GoString and Format print only the request's shape for every fmt verb, except %p on a value and a request held in an unexported struct field, which fmt prints without calling them.
Proxies ΒΆ
The default transport honors HTTPS_PROXY and NO_PROXY through http.ProxyFromEnvironment, as the standard library's default transport does. That is the standard library reading the environment, not the SDK. To bypass proxies, inject an http.Client whose transport sets no Proxy.
Where the documentation is ambiguous ΒΆ
NeverBounce's v4.2 documentation leaves some points open or contradicts itself. The SDK sends booleans as JSON true and false (the encoding rule, although one schema types them as integers); sends leverage_historical_data only when set; accepts percentages as integers or floats from 0 to 100; never decodes the results "query" echo, whose example says page 0; keeps each row's data as raw JSON, because values may come back as strings; models only the nested v4.2 status shape; keeps retry_token as opaque text it never sends back; and streams download bytes unchanged, making no claim about a header row. The units of execution_time, the time zone of the timestamps, the single-check timeout's default and range, the error format of an early download, the results' ordering, rate-limit headers or a numeric rate limit, idempotency, and the signing, ordering and delivery of job callbacks are undocumented: the SDK assumes none of them and never retries or replays a request.
Scope and extension ΒΆ
Implemented: single/check and jobs/create, parse, start, status, results and download. Not implemented: account/info, jobs/search, jobs/delete, poe/confirm, and a callback receiver. Each would be added later as one more method on Client with its own request and result types, without breaking existing callers (see docs/adding-an-operation.md in the repository).
Example (Errors) ΒΆ
Example_errors classifies failures. A *ValidationError means nothing was sent. Any other failure may follow a call the provider already processed and billed, so none of these branches resends blindly.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/mrz1836/go-neverbounce"
)
func main() {
// A loopback address with no server: even a bug could not reach the provider.
client, err := neverbounce.NewClient("secret_example0000", neverbounce.WithTestBaseURL("https://127.0.0.1:9"))
if err != nil {
fmt.Println("config:", err)
return
}
expired, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancel()
_, invalid := client.CheckEmail(context.Background(), neverbounce.CheckEmailRequest{Email: " "})
_, deadline := client.CheckEmail(expired, neverbounce.CheckEmailRequest{Email: "avery.example@example.com"})
describe := func(err error) string {
if ve, ok := errors.AsType[*neverbounce.ValidationError](err); ok {
return "nothing sent; fix " + ve.Field + " (" + ve.Reason + ")"
}
switch {
case errors.Is(err, neverbounce.ErrTimeout): // before context.DeadlineExceeded, which it also matches
return "the SDK's timeout expired; the call may already be billed"
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
return "the caller's context ended"
case errors.Is(err, neverbounce.ErrUnauthorized), errors.Is(err, neverbounce.ErrRateLimited):
return "refused; check the key or slow down"
case errors.Is(err, neverbounce.ErrBudgetExhausted), errors.Is(err, neverbounce.ErrJobFailed):
return "bulk work incomplete"
}
return "other failure"
}
for _, err := range []error{
invalid,
deadline,
// Errors as the SDK reports them, built by hand here.
&neverbounce.CallError{Kind: neverbounce.FailureTimeout, Op: neverbounce.OpCheckEmail},
&neverbounce.CallError{
Kind: neverbounce.FailureUnauthorized, Op: neverbounce.OpJobStatus, JobID: 4242,
StatusCode: http.StatusOK, APIStatus: neverbounce.APIStatusAuthFailure,
},
&neverbounce.CallError{Kind: neverbounce.FailureBudgetExhausted, Op: neverbounce.OpJobResults, JobID: 4242, Page: 3},
} {
fmt.Println(describe(err))
fmt.Println(" log line:", err)
}
}
Output: nothing sent; fix Email (blank) log line: neverbounce: invalid request: Email: blank the caller's context ended log line: neverbounce: single/check: deadline_exceeded the SDK's timeout expired; the call may already be billed log line: neverbounce: single/check: timeout refused; check the key or slow down log line: neverbounce: jobs/status: unauthorized (HTTP 200, auth_failure) bulk work incomplete log line: neverbounce: jobs/results: budget_exhausted
Example (Fake) ΒΆ
Example_fake tests application code without the provider: the application depends on a one-method interface of its own, which the real Client satisfies, and its tests pass a fake. A CallError built from its exported fields matches errors.Is like one the SDK returns.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/mrz1836/go-neverbounce"
)
// fakeChecker is an application's test fake: it returns a canned answer.
type fakeChecker struct {
res *neverbounce.CheckEmailResult
err error
}
// CheckEmail returns the canned answer.
func (f fakeChecker) CheckEmail(context.Context, neverbounce.CheckEmailRequest) (*neverbounce.CheckEmailResult, error) {
return f.res, f.err
}
func main() {
type EmailChecker interface {
CheckEmail(ctx context.Context, req neverbounce.CheckEmailRequest) (*neverbounce.CheckEmailResult, error)
}
var _ EmailChecker = (*neverbounce.Client)(nil)
var checker EmailChecker = fakeChecker{err: &neverbounce.CallError{
Kind: neverbounce.FailureRateLimited, Op: neverbounce.OpCheckEmail,
StatusCode: http.StatusOK, APIStatus: neverbounce.APIStatusThrottleTriggered,
}}
_, err := checker.CheckEmail(context.Background(), neverbounce.CheckEmailRequest{Email: "avery.example@example.com"})
fmt.Println(errors.Is(err, neverbounce.ErrRateLimited))
fmt.Println(err)
}
Output: true neverbounce: single/check: rate_limited (HTTP 200, throttle_triggered)
Example (HttpHandler) ΒΆ
Example_httpHandler serves a signup form's email check from a net/http handler, exercised here with httptest.NewRecorder.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"time"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const exCheckValid = `{"status":"success","result":"valid","flags":["has_dns","has_dns_mx"],` +
`"credits_info":{"paid_credits_used":1,"free_credits_used":0},"execution_time":7}`
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
// signupHandler is an application's handler for a signup form: it checks
// the posted address and answers with a small JSON verdict.
type signupHandler struct {
client *neverbounce.Client
}
// ServeHTTP checks the form's email field.
func (h signupHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
res, err := h.client.CheckEmail(ctx, neverbounce.CheckEmailRequest{Email: r.FormValue("email")})
switch {
case errors.Is(err, neverbounce.ErrInvalidRequest):
http.Error(w, "enter an email address", http.StatusBadRequest)
return
case err != nil:
http.Error(w, "email check unavailable", http.StatusBadGateway)
return
}
type verdict struct {
Result neverbounce.Result `json:"result"`
Suggestion string `json:"suggestion,omitempty"`
}
w.Header().Set("Content-Type", "application/json")
if err = json.NewEncoder(w).Encode(verdict{Result: res.Result, Suggestion: res.SuggestedCorrection}); err != nil {
return
}
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{neverbounce.OpCheckEmail: {exCheckValid}})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
h := signupHandler{client: client} // in an application: mux.Handle("POST /signup/check", h)
for _, email := range []string{"avery.example@example.com", ""} {
form := strings.NewReader(url.Values{"email": {email}}.Encode())
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/signup/check", form)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Print(rec.Code, " ", rec.Body.String())
}
}
Output: 200 {"result":"valid"} 400 enter an email address
Example (StoringResults) ΒΆ
Example_storingResults stores a result as JSON and reads it back unchanged: the provider's snake_case names, with an unreported counter kept apart from a zero one. Unmarshal only what the SDK returned: a raw provider body unmarshaled into these types skips every check the SDK makes.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const exCheckValid = `{"status":"success","result":"valid","flags":["has_dns","has_dns_mx"],` +
`"credits_info":{"paid_credits_used":1,"free_credits_used":0},"execution_time":7}`
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{neverbounce.OpCheckEmail: {exCheckValid}})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
res, err := client.CheckEmail(context.Background(), neverbounce.CheckEmailRequest{
Email: "avery.example@example.com", CreditsInfo: true,
})
if err != nil {
fmt.Println("check:", err)
return
}
stored, err := json.Marshal(res)
if err != nil {
fmt.Println("store:", err)
return
}
var loaded neverbounce.CheckEmailResult
if err = json.Unmarshal(stored, &loaded); err != nil {
fmt.Println("load:", err)
return
}
fmt.Println(string(stored))
fmt.Println("unchanged:", reflect.DeepEqual(*res, loaded))
}
Output: {"result":"valid","flags":["has_dns","has_dns_mx"],"credits_info":{"paid_credits_used":1,"free_credits_used":0},"execution_time":7} unchanged: true
Index ΒΆ
- Constants
- Variables
- type APIStatus
- type AddressInfo
- type BinaryFormat
- type CallError
- type CheckEmailRequest
- type CheckEmailResult
- type Client
- func (c *Client) CheckEmail(ctx context.Context, req CheckEmailRequest) (*CheckEmailResult, error)
- func (c *Client) CreateJob(ctx context.Context, req CreateJobRequest) (*CreateJobResult, error)
- func (c *Client) DownloadJob(ctx context.Context, req DownloadJobRequest, w io.Writer) (int64, error)
- func (c *Client) GoString() string
- func (c *Client) JobResultPages(ctx context.Context, req JobResultPagesRequest) iter.Seq2[*JobResultsPage, error]
- func (c *Client) JobResults(ctx context.Context, req JobResultsRequest) (*JobResultsPage, error)
- func (c *Client) JobStatus(ctx context.Context, req JobStatusRequest) (*JobStatus, error)
- func (c *Client) ParseJob(ctx context.Context, req ParseJobRequest) (*ParseJobResult, error)
- func (c *Client) StartJob(ctx context.Context, req StartJobRequest) (*StartJobResult, error)
- func (c *Client) String() string
- func (c *Client) WaitForJob(ctx context.Context, req WaitForJobRequest) (*JobStatus, error)
- type CreateJobRequest
- type CreateJobResult
- type CreditsInfo
- type DownloadColumns
- type DownloadJobRequest
- type DownloadSegments
- type FailureKind
- type Flag
- type Flags
- type JobFailureReason
- type JobID
- type JobResultPagesRequest
- type JobResultsPage
- type JobResultsRequest
- type JobState
- type JobStatus
- type JobStatusRequest
- type JobTotals
- type LineFeed
- type Operation
- type Option
- type ParseJobRequest
- type ParseJobResult
- type ProviderDiagnostics
- type Result
- type ResultRow
- type RowVerification
- type StartJobRequest
- type StartJobResult
- type SuppliedList
- type ValidationError
- type WaitForJobRequest
Examples ΒΆ
Constants ΒΆ
const ( // DefaultTimeout bounds each JSON call, including reading the whole // response body. WithTimeout accepts more than 0 and at most 10 minutes. DefaultTimeout = 60 * time.Second // DefaultMaxResponseBytes limits a JSON response body. WithMaxResponseBytes // accepts 1 byte to 64 MiB. Every operation except jobs/results is also // capped at 1 MiB, far above any documented answer. DefaultMaxResponseBytes = 8 << 20 // DefaultDownloadTimeout bounds a whole DownloadJob call, streaming // included. WithDownloadTimeout accepts more than 0 and at most 12 hours. DefaultDownloadTimeout = 30 * time.Minute // DefaultMaxDownloadBytes limits the bytes DownloadJob copies to its // writer. WithMaxDownloadBytes accepts 1 byte to 64 GiB. DefaultMaxDownloadBytes = 1 << 30 // MaxJobRequestBytes is the provider's 25 MB jobs/create limit, read as // 25,000,000 bytes (the smaller reading) for the whole encoded request // body, the API key included. CreateJob rejects a larger body locally. MaxJobRequestBytes = 25_000_000 // MaxItemsPerPage is the largest items_per_page jobs/results accepts. MaxItemsPerPage = 1000 // DefaultWaitInterval is WaitForJob's pause between polls when // WaitForJobRequest.Interval is 0. DefaultWaitInterval = 10 * time.Second // DefaultPageSize is the items_per_page JobResultPages sends when // JobResultPagesRequest.ItemsPerPage is 0. DefaultPageSize = 100 )
Defaults and limits.
Variables ΒΆ
var ( // ErrInvalidConfig reports an invalid NewClient argument or option, or a // Client that was not created by NewClient. No request was sent. ErrInvalidConfig = errors.New("neverbounce: invalid configuration") // ErrInvalidRequest reports a request that fails local validation, or a nil // context. No request was sent. ErrInvalidRequest = errors.New("neverbounce: invalid request") // auth_failure or bad_referrer, or HTTP 401 or 403. ErrUnauthorized = errors.New("neverbounce: unauthorized") // ErrRateLimited reports the envelope status throttle_triggered or HTTP // 429. The SDK never retries. ErrRateLimited = errors.New("neverbounce: rate limited") // partial service interruption on the provider's side. ErrUnavailable = errors.New("neverbounce: temporarily unavailable") // ErrRejected reports a refused request: the envelope status // general_failure, or an HTTP 4xx status other than 401, 403 and 429 (413, // for a jobs/create body over the provider's limit, included). ErrRejected = errors.New("neverbounce: rejected by provider") // ErrUpstream reports an HTTP 5xx status other than 503. ErrUpstream = errors.New("neverbounce: provider server error") // ErrUnexpectedResponse reports a response this SDK cannot interpret: an // HTTP status that is not 200 and not 4xx or 5xx (a redirect, which is // never followed, included), a body that is not a JSON object, an // undocumented envelope status, a value that breaks the documented shape // (an invalid token, a job ID other than the one requested, a results page // with more rows than requested or that contradicts an earlier one), an // undecoded Content-Encoding, or a download that is not a file: a content // type other than CSV, a success envelope instead of the file, or a JSON // answer over 64 KiB. The provider may already have processed the request. ErrUnexpectedResponse = errors.New("neverbounce: unexpected response") // ErrMalformedResponse reports an HTTP 200 body that is not valid UTF-8 // or valid JSON, has data after the top-level value, repeats a key, lacks // a required field, or holds a field of the wrong JSON type or out of // range. The provider may already have processed the request. ErrMalformedResponse = errors.New("neverbounce: malformed response") // ErrResponseTooLarge reports a response larger than a configured limit // (WithMaxResponseBytes, WithMaxDownloadBytes), than the fixed 1 MiB cap // on every JSON answer except jobs/results, or than an SDK safety bound: // 100,000 JSON objects and arrays or 1,000,000 values in one body, or one // field over its bound. The provider may already have processed the // request. ErrResponseTooLarge = errors.New("neverbounce: response too large") // ErrTransport reports a failure in transit, such as DNS, connection, TLS // or proxy errors, a reset, a truncated body, or a stalled body (100 reads // in a row that return nothing). The request may or may not have reached // the provider. ErrTransport = errors.New("neverbounce: transport failure") // ErrTimeout reports that the SDK's own timeout (WithTimeout, // WithDownloadTimeout) or an injected http.Client's Timeout expired, or // that the network reported a timeout. It also matches // context.DeadlineExceeded, so check it first to tell it apart from the // caller's own deadline. The provider may already have processed the // request. ErrTimeout = errors.New("neverbounce: timeout") // ErrWriteFailed reports that DownloadJob's writer returned an error or // wrote fewer bytes than it was given. The writer's own error is not // kept: wrap the writer to capture it. ErrWriteFailed = errors.New("neverbounce: download write failed") // ErrJobFailed reports that WaitForJob observed the job_status "failed". // The returned *JobStatus carries the provider's FailureReason. ErrJobFailed = errors.New("neverbounce: job failed") // ErrUnknownJobState reports that WaitForJob observed an undocumented // job_status. The SDK surfaces it rather than polling through it. ErrUnknownJobState = errors.New("neverbounce: unknown job state") // ErrBudgetExhausted reports that a helper used up its budget: WaitForJob's // MaxWait, or JobResultPages' MaxPages while more pages remain. ErrBudgetExhausted = errors.New("neverbounce: budget exhausted") )
Sentinel errors. Match them with errors.Is.
ErrInvalidConfig and ErrInvalidRequest are local: an error matching either means no request was sent. Every other sentinel describes a call that was attempted, or a helper that stopped short; after an attempted call the provider may already have processed it, billed it or started a job.
Functions ΒΆ
This section is empty.
Types ΒΆ
type APIStatus ΒΆ
type APIStatus string
APIStatus is the "status" member of a provider response envelope. A CallError keeps an undocumented value too, but only when it is 1 to 64 bytes of lowercase ASCII letters and underscores, and never when it contains the API key.
const ( // APIStatusSuccess means the request succeeded. APIStatusSuccess APIStatus = "success" // APIStatusGeneralFailure means the request failed; the provider's message // says why (see WithProviderDiagnostics). APIStatusGeneralFailure APIStatus = "general_failure" // APIStatusAuthFailure means the API key was refused. APIStatusAuthFailure APIStatus = "auth_failure" APIStatusTempUnavail APIStatus = "temp_unavail" // APIStatusThrottleTriggered means the request was rate limited. APIStatusThrottleTriggered APIStatus = "throttle_triggered" // APIStatusBadReferrer means the request's referrer is not trusted. APIStatusBadReferrer APIStatus = "bad_referrer" )
Documented envelope statuses.
type AddressInfo ΒΆ
type AddressInfo struct {
OriginalEmail string `json:"original_email,omitempty"`
NormalizedEmail string `json:"normalized_email,omitempty"`
Addr string `json:"addr,omitempty"`
Alias string `json:"alias,omitempty"`
Host string `json:"host,omitempty"`
FQDN string `json:"fqdn,omitempty"`
Domain string `json:"domain,omitempty"`
Subdomain string `json:"subdomain,omitempty"`
TLD string `json:"tld,omitempty"`
}
AddressInfo is the provider's parse of the address ("address_info"). Every field is provider text, never checked or normalized by the SDK; "" means absent, null or empty.
type BinaryFormat ΒΆ
type BinaryFormat string
BinaryFormat is how a download spells yes/no columns ("binary_operators_type").
const ( BinaryOneZero BinaryFormat = "BIN_1_0" // 1 and 0, the provider's default BinaryUpperYN BinaryFormat = "BIN_Y_N" BinaryLowerYN BinaryFormat = "BIN_y_n" BinaryLowerYesNo BinaryFormat = "BIN_yes_no" BinaryTitleYesNo BinaryFormat = "BIN_Yes_No" BinaryLowerTrueFalse BinaryFormat = "BIN_true_false" )
Binary formats.
type CallError ΒΆ
type CallError struct {
// Kind classifies the failure.
Kind FailureKind
// Op is the operation concerned.
Op Operation
// StatusCode is the HTTP status, or 0 when no response was received (and
// for the helper kinds job_failed, unknown_job_state and budget_exhausted).
StatusCode int
// APIStatus is the envelope status, kept when it is 1 to 64 bytes of
// lowercase ASCII letters and underscores and does not contain the API
// key, and "" otherwise.
APIStatus APIStatus
// JobID is the job concerned when it is known: 0 for single/check, and
// for a jobs/create whose answer could not be read.
JobID JobID
// Page is the jobs/results page requested; for budget_exhausted from
// JobResultPages, it is the next page, where a new iteration can resume.
Page int
// Field is a JSON path, such as "results[3].verification.result", for
// type and shape failures. It names a location, never a value.
Field string
// BytesWritten is the number of bytes DownloadJob wrote to its writer
// before failing. It is 0 for every other operation.
BytesWritten int64
// contains filtered or unexported fields
}
CallError describes a call that was attempted, a call that a canceled or expired context stopped before it was sent, or a helper (WaitForJob, JobResultPages) that stopped short.
Its Error text is built only from Op, Kind, StatusCode, APIStatus and Field: it never holds the API key, email addresses, row data, URLs, header values, response bodies or provider messages, so it is safe to log. GoString and every fmt verb add only the other exported fields. The cause and the provider diagnostics sit behind a function value that fmt and reflection-based dumpers print only as an address.
Tests and fakes may build a CallError from its exported fields alone; it then matches errors.Is like one the SDK returns.
Example ΒΆ
ExampleCallError reads a failed call. Its Error text holds only the operation, the kind, the HTTP status, the provider's status token and a field path, so it is safe to log. The provider's message is kept only with WithProviderDiagnostics.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const exThrottled = `{"status":"throttle_triggered","message":"Synthetic: too many requests, slow down."}`
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{neverbounce.OpCheckEmail: {exThrottled}})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
neverbounce.WithProviderDiagnostics(),
)
if err != nil {
fmt.Println("config:", err)
return
}
_, err = client.CheckEmail(context.Background(), neverbounce.CheckEmailRequest{Email: "avery.example@example.com"})
fmt.Println("log line:", err)
fmt.Println("rate limited:", errors.Is(err, neverbounce.ErrRateLimited)) // the SDK never retries
if ce, ok := errors.AsType[*neverbounce.CallError](err); ok {
fmt.Println(ce.Op, ce.Kind, ce.StatusCode, ce.APIStatus)
fmt.Println("provider says:", ce.Diagnostics().Message) // may echo request data: think before logging
}
}
Output: log line: neverbounce: single/check: rate_limited (HTTP 200, throttle_triggered) rate limited: true single/check rate_limited 200 throttle_triggered provider says: Synthetic: too many requests, slow down.
func (*CallError) Diagnostics ΒΆ
func (e *CallError) Diagnostics() ProviderDiagnostics
Diagnostics returns the provider's message for this failure. It is empty unless the Client was created with WithProviderDiagnostics. Provider text may echo request data, such as an email address: inspect it, but think before logging or storing it.
func (*CallError) Error ΒΆ
Error returns "neverbounce: <op>: <kind>", followed by " (HTTP <status>, <api status>)" with whichever of the two is known, and ": <field>" when a field is named, such as "neverbounce: jobs/status: rate_limited (HTTP 200, throttle_triggered)".
func (*CallError) GoString ΒΆ
GoString prints the exported metadata only, so that %#v cannot reach the cause or the provider diagnostics.
func (*CallError) Is ΒΆ
Is reports whether target is the sentinel for e.Kind. A timeout also matches context.DeadlineExceeded, a caller deadline matches context.DeadlineExceeded and a cancellation matches context.Canceled.
func (*CallError) Unwrap ΒΆ
Unwrap returns the sanitized cause: a context error or a fixed error of this package. It is never a *url.Error, a JSON decoding error, the writer's error or anything else that could quote a URL, a header or response content. It is nil for a CallError built from its exported fields.
type CheckEmailRequest ΒΆ
type CheckEmailRequest struct {
// Email is the address to verify, sent verbatim: never trimmed,
// normalized or checked against an RFC. It must be 1 to 1024 bytes of
// valid UTF-8 without control characters, and not only whitespace. A
// malformed address is a legitimate input: the provider answers it (and
// bills it) like any other.
Email string
// AddressInfo asks for the provider's parse of the address
// (CheckEmailResult.AddressInfo). It is always sent, false included.
AddressInfo bool
// CreditsInfo asks for the account's credit counters
// (CheckEmailResult.CreditsInfo). It is always sent, false included.
CreditsInfo bool
// Timeout is the provider's server-side verification timeout, sent as
// "timeout" in whole seconds. 0 means not sent (the provider's default,
// which is undocumented). When it expires the provider answers
// ResultUnknown, and the whole request can take longer than it. It must
// be whole seconds from 1s to 300s, and at least 10 seconds shorter than
// the Client's WithTimeout, so that the SDK does not give up on a check the
// provider will still bill.
Timeout time.Duration
// LeverageHistoricalData, when non-nil, is sent as
// request_meta_data.leverage_historical_data; false asks for real-time
// verification only. nil is not sent (the provider's default is true).
// It is documented in the v4.1 changelog for single checks and in the
// v4.2 jobs/create schema, but not in the v4.2 single/check schema.
LeverageHistoricalData *bool
}
CheckEmailRequest is one single/check call. It is read only while CheckEmail encodes it, before any I/O, and is never kept or modified.
type CheckEmailResult ΒΆ
type CheckEmailResult struct {
// Result is the verdict. ResultUnknown is a successful answer.
Result Result `json:"result"`
// Flags are the provider's observations, in its order. nil when none.
Flags Flags `json:"flags,omitempty"`
// SuggestedCorrection is the provider's soft suggestion for a likely typo,
// such as a misspelled domain, or "". The SDK never applies it or checks
// the suggestion.
SuggestedCorrection string `json:"suggested_correction,omitempty"`
// AddressInfo is the provider's parse of the address, when reported (ask
// for it with CheckEmailRequest.AddressInfo), and nil otherwise.
AddressInfo *AddressInfo `json:"address_info,omitempty"`
// CreditsInfo is the account's credit counters, when reported (ask for
// them with CheckEmailRequest.CreditsInfo), and nil otherwise.
CreditsInfo *CreditsInfo `json:"credits_info,omitempty"`
// RetryToken is the provider's retry_token, kept as opaque text when it is
// a string of at most 1 KiB. It appears only in a provider guide example:
// the SDK gives it no meaning and never sends it back.
RetryToken string `json:"retry_token,omitempty"`
// ExecutionTime is the provider's execution_time, when it is an integer of
// at least 0. Its units are undocumented.
ExecutionTime *int64 `json:"execution_time,omitempty"`
}
CheckEmailResult is the provider's answer to one single/check call. It holds contact data (the address and its parse): treat it as personal data.
It survives a JSON round trip through encoding/json unchanged, under the provider's snake_case names. Unmarshaling a raw provider body into it skips every check the SDK makes.
type Client ΒΆ
type Client struct {
// contains filtered or unexported fields
}
Client calls the NeverBounce API v4.2. Create it with NewClient; the zero Client and a nil *Client return ErrInvalidConfig without any I/O. A Client is immutable and safe for concurrent use.
Its fields are unexported and the API key is held only inside function values, so formatting a Client, or a struct holding one, with any fmt verb or a reflection-based dumper never prints it.
func NewClient ΒΆ
NewClient returns a Client that authenticates with a NeverBounce v4 API key.
Parameters:
- apiKey: the key from the NeverBounce dashboard, sent as the first member ("key") of every JSON request body, never in a URL or header
- opts: optional settings; see the With functions
The key must be 1 to 256 bytes of visible ASCII (0x21 to 0x7E) other than '"' and '\'. Its "secret_" prefix is not enforced. The application decides where the key comes from: NewClient reads no environment variables or files and performs no I/O.
Errors are *ValidationError values matching ErrInvalidConfig. They name the argument or option, never its value.
Example ΒΆ
ExampleNewClient builds a client once, to be shared: it is safe for concurrent use. NewClient makes no call and reads no environment variable or file: the application decides where the key comes from.
package main
import (
"fmt"
"net/http"
"time"
"github.com/mrz1836/go-neverbounce"
)
func main() {
apiKey := "secret_example0000" // from your application's secret store
sharedHTTPClient := &http.Client{} // your own transport settings, if any
client, err := neverbounce.NewClient(apiKey,
neverbounce.WithTimeout(45*time.Second),
neverbounce.WithHTTPClient(sharedHTTPClient), // copied; redirects refused; never mutated
)
if err != nil {
fmt.Println("config:", err) // names the option, never the key
return
}
fmt.Println(client) // settings only, never the key
_, err = neverbounce.NewClient(apiKey, neverbounce.WithTimeout(time.Hour))
fmt.Println(err)
}
Output: neverbounce.Client{timeout: 45s, maxResponseBytes: 8388608, downloadTimeout: 30m0s, maxDownloadBytes: 1073741824, testBaseURL: false, providerDiagnostics: false} neverbounce: invalid configuration: Timeout: out_of_range
func (*Client) CheckEmail ΒΆ
func (c *Client) CheckEmail(ctx context.Context, req CheckEmailRequest) (*CheckEmailResult, error)
CheckEmail verifies one address: POST https://api.neverbounce.com/v4.2/single/check.
PAID: every call costs one credit, duplicates and syntactically bad addresses included. It makes exactly one attempt and never retries. After a timeout, cancellation, transport failure or unreadable response the check may already be billed: do not resend it blindly. ResultUnknown is a successful answer, never an error.
The provider's usage guidelines forbid verifying an existing list one address at a time: use CreateJob for lists.
Errors are a *ValidationError (nothing sent) or a *CallError.
Example ΒΆ
ExampleClient_CheckEmail verifies one address. Every check is billed one credit, whatever its result.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const exCheckTypo = `{"status":"success","result":"invalid",` +
`"flags":["has_dns","has_dns_mx","spelling_mistake"],` +
`"suggested_correction":"avery.example@example.com",` +
`"address_info":{"original_email":"avery.example@example.net",` +
`"normalized_email":"avery.example@example.net","addr":"avery.example","alias":"",` +
`"host":"example.net","fqdn":"example.net","domain":"example","subdomain":"","tld":"net"},` +
`"credits_info":{"paid_credits_used":1,"free_credits_used":0,` +
`"paid_credits_remaining":4999,"free_credits_remaining":0},"execution_time":412}`
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{neverbounce.OpCheckEmail: {exCheckTypo}})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
res, err := client.CheckEmail(context.Background(), neverbounce.CheckEmailRequest{
Email: "avery.example@example.net",
AddressInfo: true,
CreditsInfo: true,
Timeout: 20 * time.Second, // the provider's own verification timeout
})
if err != nil {
fmt.Println("check:", err) // it may already be billed: never resend blindly
return
}
switch {
case res.Result == neverbounce.ResultUnknown:
fmt.Println("unknown: a valid answer, not an error")
case !res.Result.Known():
fmt.Println("undocumented result, kept as sent:", res.Result)
default:
fmt.Println("result:", res.Result)
}
fmt.Println("flags:", res.Flags)
fmt.Println("spelling mistake:", res.Flags.Has(neverbounce.FlagSpellingMistake))
if res.SuggestedCorrection != "" {
fmt.Println("did you mean:", res.SuggestedCorrection) // a suggestion: never applied or rechecked
}
if ai := res.AddressInfo; ai != nil {
fmt.Println("host:", ai.Host, "normalized:", ai.NormalizedEmail)
}
if ci := res.CreditsInfo; ci != nil && ci.PaidCreditsRemaining != nil {
fmt.Println("paid credits remaining:", *ci.PaidCreditsRemaining)
}
}
Output: result: invalid flags: [has_dns has_dns_mx spelling_mistake] spelling mistake: true did you mean: avery.example@example.com host: example.net normalized: avery.example@example.net paid credits remaining: 4999
func (*Client) CreateJob ΒΆ
func (c *Client) CreateJob(ctx context.Context, req CreateJobRequest) (*CreateJobResult, error)
CreateJob creates a bulk verification job: POST https://api.neverbounce.com/v4.2/jobs/create.
STATE-CHANGING, and PAID when AutoStart is true: the job is durable, and with AutoStart the provider deducts credits for the list's billable count as soon as parsing ends. Without AutoStart nothing is billed until StartJob, or ParseJob with AutoStart. It makes exactly one attempt and never retries. After a timeout, cancellation, transport failure or unreadable response a job may exist anyway, possibly started: do not resubmit blindly; look for its Filename in the dashboard first.
The provider's usage guidelines allow 10 concurrent jobs and 50 runs a day, no more than 10 jobs per 100,000 items per hour, and suggest chunks of at most 1 million addresses. The SDK documents these and enforces none.
Errors are a *ValidationError (nothing sent) or a *CallError.
Example ΒΆ
ExampleClient_CreateJob verifies a list deliberately: create it with parsing only, wait until it is parsed, check the billable count against a budget, then start it explicitly and wait for the results.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const (
exCreated = `{"status":"success","job_id":4242,"execution_time":31}`
exStarted = `{"status":"success","queue_id":"NB-EXAMPLE-QUEUE","execution_time":12}`
exStatusParsed = `{"status":"success","id":4242,"job_status":"waiting","filename":"signups-2026-10-15-a7f3",` +
`"total":{"records":2,"billable":2,"processed":0},"percent_complete":0}`
exStatusDone = `{"status":"success","id":4242,"job_status":"complete","filename":"signups-2026-10-15-a7f3",` +
`"total":{"records":2,"billable":2,"processed":2,"valid":1,"invalid":0,"catchall":1},` +
`"bounce_estimate":0,"percent_complete":100}`
)
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{
neverbounce.OpCreateJob: {exCreated},
neverbounce.OpJobStatus: {exStatusParsed, exStatusDone},
neverbounce.OpStartJob: {exStarted},
})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
ctx := context.Background()
const budget = 500 // the most credits this list may use
created, err := client.CreateJob(ctx, neverbounce.CreateJobRequest{
Supplied: neverbounce.SuppliedList{
Columns: []string{"id", "email"},
Rows: [][]string{{"1001", "avery.example@example.com"}, {"1002", "blake.example@example.org"}},
},
Filename: "signups-2026-10-15-a7f3", // unique: findable in the dashboard after an ambiguous create
AutoParse: true, // AutoStart false is sent explicitly: nothing is billed yet
})
if err != nil {
fmt.Println("create:", err) // a job may exist anyway: look for its Filename before resubmitting
return
}
st, err := client.WaitForJob(ctx, neverbounce.WaitForJobRequest{JobID: created.JobID, MaxWait: 15 * time.Minute})
if err != nil {
fmt.Println("parse:", err) // st, when not nil, is the last status read
return
}
if st.State != neverbounce.JobStateWaiting || st.Totals.Billable == nil || *st.Totals.Billable > budget {
fmt.Println("not starting job", created.JobID, "in state", st.State)
return
}
fmt.Println("job", created.JobID, "is parsed; billable:", *st.Totals.Billable)
// PAID AND IRREVERSIBLE: the provider deducts credits for the billable count.
if _, err = client.StartJob(ctx, neverbounce.StartJobRequest{JobID: created.JobID}); err != nil {
fmt.Println("start:", err) // it may have started anyway: read JobStatus before ever starting again
return
}
st, err = client.WaitForJob(ctx, neverbounce.WaitForJobRequest{
JobID: created.JobID, Interval: 15 * time.Second, MaxWait: 2 * time.Hour,
})
if err != nil {
fmt.Println("verify:", err)
return
}
fmt.Println("job", created.JobID, "is", st.State)
}
Output: job 4242 is parsed; billable: 2 job 4242 is complete
func (*Client) DownloadJob ΒΆ
func (c *Client) DownloadJob(ctx context.Context, req DownloadJobRequest, w io.Writer) (int64, error)
DownloadJob streams a job's results, a CSV file, to w: POST https://api.neverbounce.com/v4.2/jobs/download. It returns the number of bytes written to w, on error too.
Free and read-only. It makes exactly one attempt and never retries or resumes. The response is classified before any byte reaches w: an HTTP status other than 200, a JSON envelope (such as a job that is not complete), a content type other than application/octet-stream or text/csv, and a declared length over WithMaxDownloadBytes all write nothing. The bytes are then copied unchanged: no CSV parsing, no BOM, no line-ending rewrite.
w belongs to the caller: the SDK never closes, flushes or inspects it. On any error after streaming began, w holds a partial file of BytesWritten bytes: discard it. WithDownloadTimeout bounds the whole call; WithMaxDownloadBytes bounds the bytes written, and a longer download fails with ErrResponseTooLarge after exactly that many. Canceling ctx stops the download at its next read, but cannot interrupt a Write to w that blocks.
Errors are a *ValidationError (nothing sent) or a *CallError whose JobID is req.JobID and whose BytesWritten is the count returned.
Example ΒΆ
ExampleClient_DownloadJob streams a job's results, a CSV file, into a writer the caller owns.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const exCSV = "id,email,email_status\r\n" +
"1001,avery.example@example.com,valid\r\n" +
"1002,blake.example@example.org,catchall\r\n"
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{neverbounce.OpDownloadJob: {exCSV}})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
// file stands in for a file the application creates, such as one from
// os.Create. The SDK never closes, flushes or removes it.
var file bytes.Buffer
n, err := client.DownloadJob(context.Background(), neverbounce.DownloadJobRequest{
JobID: 4242,
Append: neverbounce.DownloadColumns{EmailStatus: new(true)},
LineFeed: neverbounce.LineFeedCRLF, // the provider's default, "\n\r", trips encoding/csv
}, &file)
if err != nil {
file.Reset() // discard the partial file (n bytes): never append a second attempt to it
fmt.Println("download:", err, "after", n, "bytes")
return
}
fmt.Println("bytes written:", n)
for line := range strings.Lines(file.String()) {
fmt.Printf("%q\n", line)
}
}
Output: bytes written: 102 "id,email,email_status\r\n" "1001,avery.example@example.com,valid\r\n" "1002,blake.example@example.org,catchall\r\n"
func (*Client) GoString ΒΆ
GoString returns the same text as String, so that %#v prints settings only.
func (*Client) JobResultPages ΒΆ
func (c *Client) JobResultPages(ctx context.Context, req JobResultPagesRequest) iter.Seq2[*JobResultsPage, error]
JobResultPages returns an iterator over a job's result pages, from StartPage on.
Free and read-only: it only ever calls jobs/results, one call per page, each made only after the previous page was yielded and the loop continued. Nothing is prefetched, nothing runs in the background, and breaking out of the loop stops it at once. Each range starts again at StartPage with new calls. The page counter is the SDK's own, so the walk can never loop.
The first page is yielded even when it is empty because the job has no results (TotalPages 0) or StartPage is past the end; the walk then ends after the page whose number reaches TotalPages. An error is yielded once, as (nil, err), and ends the walk; pages already yielded stay valid:
- a *ValidationError, before any call;
- a page's *CallError, with JobID and Page set;
- unexpected_response when a page contradicts the walk: TotalPages or TotalResults changed since the first page, an empty page before the last, rows past the last page, or more pages than jobs/results can number (it takes a 32-bit page number);
- budget_exhausted when MaxPages pages were read and more remain. Its Page is the next page: a new walk with that StartPage resumes there.
Example ΒΆ
ExampleClient_JobResultPages walks a job's result pages within a page budget, resumes where the budget ran out, and stops early with break.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"github.com/mrz1836/go-neverbounce"
)
// exPage returns a synthetic jobs/results answer: page n of 4, with one row.
func exPage(n int) string {
return fmt.Sprintf(`{"status":"success","total_results":4,"total_pages":4,"results":[`+
`{"data":{"id":"%d"},"verification":{"result":"valid"}}]}`, 1000+n)
}
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{
neverbounce.OpJobResults: {exPage(1), exPage(2), exPage(3), exPage(4)},
})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
ctx := context.Background()
const want = 3 // rows this run stores; a later run goes on from there
stored := 0
req := neverbounce.JobResultPagesRequest{JobID: 4242, ItemsPerPage: 1, MaxPages: 2}
for page, err := range client.JobResultPages(ctx, req) {
if ce, ok := errors.AsType[*neverbounce.CallError](err); ok && ce.Kind == neverbounce.FailureBudgetExhausted {
fmt.Println("page budget used up; resume at page", ce.Page)
req.StartPage = ce.Page // the pages before it were already handled
break
}
if err != nil {
fmt.Println("results:", err) // pages already handled stay handled
return
}
id, _ := page.Results[0].Column("id")
fmt.Printf("page %d of %d: id %s\n", page.Page, page.TotalPages, id)
stored += len(page.Results)
}
// Resume where the budget ran out.
for page, err := range client.JobResultPages(ctx, req) {
if err != nil {
fmt.Println("results:", err)
return
}
id, _ := page.Results[0].Column("id")
fmt.Printf("page %d of %d: id %s\n", page.Page, page.TotalPages, id)
if stored += len(page.Results); stored >= want {
break // the walk stops at once: page 4 is never requested
}
}
}
Output: page 1 of 4: id 1001 page 2 of 4: id 1002 page budget used up; resume at page 3 page 3 of 4: id 1003
func (*Client) JobResults ΒΆ
func (c *Client) JobResults(ctx context.Context, req JobResultsRequest) (*JobResultsPage, error)
JobResults reads one page of a job's results: POST https://api.neverbounce.com/v4.2/jobs/results.
Free and read-only. It makes exactly one attempt and never retries, and it never reads another page on its own: see JobResultPages for a bounded walk. The page may hold at most ItemsPerPage rows (1000 when not sent); more fails as unexpected_response.
Errors are a *ValidationError (nothing sent) or a *CallError whose JobID and Page are the request's.
Example ΒΆ
ExampleClient_JobResults reads one page of results and matches each row to the application's own record through a column it submitted.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const exResults = `{"status":"success","total_results":3,"total_pages":1,"query":{"page":0},"results":[` +
`{"data":{"id":"id","email":"email"},"verification":{"result":"invalid"}},` +
`{"data":{"id":"1001","email":"avery.example@example.com"},"verification":{"result":"valid"}},` +
`{"data":{"id":1002,"email":"blake.example@example.org"},"verification":{"result":"catchall"}}]}`
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{neverbounce.OpJobResults: {exResults}})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
signups := map[string]string{"1001": "Avery", "1002": "Blake"} // your records, by the id you submitted
page, err := client.JobResults(context.Background(), neverbounce.JobResultsRequest{
JobID: 4242, Page: 1, ItemsPerPage: 500,
})
if err != nil {
fmt.Println("results:", err)
return
}
fmt.Printf("page %d of %d, %d results\n", page.Page, page.TotalPages, page.TotalResults)
for _, row := range page.Results {
// Correlate by your own column, never by position: the provider may
// return the header row as a record, and may return duplicates.
id, _ := row.Column("id")
name, ok := signups[id]
if !ok {
fmt.Printf("skipped a row that is not one of yours (id %q)\n", id)
continue
}
fmt.Println(name, row.Verification.Result)
}
}
Output: page 1 of 1, 3 results skipped a row that is not one of yours (id "id") Avery valid Blake catchall
func (*Client) JobStatus ΒΆ
JobStatus reads a job's status: POST https://api.neverbounce.com/v4.2/jobs/status.
Free and read-only. It makes exactly one attempt and never retries. An answer for any job other than req.JobID fails as unexpected_response, so a caller, and WaitForJob, can never follow another job.
Errors are a *ValidationError (nothing sent) or a *CallError whose JobID is req.JobID.
func (*Client) ParseJob ΒΆ
func (c *Client) ParseJob(ctx context.Context, req ParseJobRequest) (*ParseJobResult, error)
ParseJob parses a job created without AutoParse: POST https://api.neverbounce.com/v4.2/jobs/parse.
STATE-CHANGING, and PAID when AutoStart is true. A list cannot be parsed twice. It makes exactly one attempt and never retries; after an ambiguous failure, read JobStatus before calling it again.
Errors are a *ValidationError (nothing sent) or a *CallError whose JobID is req.JobID.
func (*Client) StartJob ΒΆ
func (c *Client) StartJob(ctx context.Context, req StartJobRequest) (*StartJobResult, error)
StartJob starts a parsed job: POST https://api.neverbounce.com/v4.2/jobs/start.
PAID AND IRREVERSIBLE unless RunSample is true: a full start deducts credits for the provider's billable count (see JobStatus Totals.Billable), and the job cannot be stopped or restarted. A sample start is free. It makes exactly one attempt and never retries. After any error, a timeout included, the job may already be queued and billed: read JobStatus before ever starting it again.
Errors are a *ValidationError (nothing sent) or a *CallError whose JobID is req.JobID.
func (*Client) String ΒΆ
String describes the Client's settings, such as "neverbounce.Client{timeout: 1m0s, maxResponseBytes: 8388608, ...}". It never includes the API key or the base URL.
func (*Client) WaitForJob ΒΆ
WaitForJob polls jobs/status for an existing job until it no longer needs the provider's attention, and returns the last status it read.
Free and read-only: it only ever calls jobs/status, first immediately and then Interval after each poll ends, and it never creates, parses, starts, resubmits or deletes a job, nor infers completion from PercentComplete. It starts no background goroutine of its own. It returns:
- (status, nil) for JobStateComplete, JobStateWaiting (call StartJob) and JobStateWaitingAnalyzed (a sample is done; a full StartJob is needed);
- (status, *CallError{Kind: job_failed}) for JobStateFailed, with the provider's reason in status.FailureReason;
- (status, *CallError{Kind: unknown_job_state}) for an undocumented state, which it surfaces rather than polls through;
- (last, *CallError{Kind: budget_exhausted}) when MaxWait ends: no poll starts at or after it, and one still running then is cut off, so it makes at most ceil(MaxWait/Interval) polls;
- (last, a canceled or deadline_exceeded *CallError) when ctx ends;
- (last, err) when a poll fails before MaxWait: it never retries, so polling policy stays the caller's.
last is the last status read, or nil when there was none. Canceling ctx stops the polling, never the job or its billing. Errors that are not a *ValidationError carry Op jobs/status and JobID req.JobID.
Example ΒΆ
ExampleClient_WaitForJob polls a job's status until it needs you, has ended, or the wait budget is used up. It only reads the status: it never starts, resubmits or stops a job.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
"github.com/mrz1836/go-neverbounce"
)
// Synthetic provider answers for the examples. They follow the documented
// v4.2 shapes, but every value is made up.
const exStatusSampled = `{"status":"success","id":4242,"job_status":"waiting_analyzed",` +
`"total":{"records":2,"billable":2},"bounce_estimate":12.5,"percent_complete":100}`
// exServer starts a local TLS server that stands in for NeverBounce, so the
// examples run offline, need no key and cost nothing. It answers each
// operation with the bodies given for it in turn, repeating the last one; for
// jobs/results it answers with the body for the page requested. Bodies are
// JSON, except for jobs/download, which answers with a CSV file.
func exServer(answers map[neverbounce.Operation][]string) *httptest.Server {
var mu sync.Mutex
calls := map[neverbounce.Operation]int{}
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
op := neverbounce.Operation(strings.TrimPrefix(r.URL.Path, "/v4.2/"))
var req struct {
Page int `json:"page"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "not JSON", http.StatusBadRequest)
return
}
mu.Lock()
i := calls[op]
calls[op]++
mu.Unlock()
if op == neverbounce.OpJobResults {
i = max(req.Page, 1) - 1
}
bodies := answers[op]
if len(bodies) == 0 {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if op == neverbounce.OpDownloadJob {
w.Header().Set("Content-Type", "application/octet-stream")
}
_, _ = io.WriteString(w, bodies[min(i, len(bodies)-1)])
}))
}
func main() {
srv := exServer(map[neverbounce.Operation][]string{neverbounce.OpJobStatus: {exStatusSampled}})
defer srv.Close()
// A real application passes its own key and leaves out the two test options.
client, err := neverbounce.NewClient("secret_example0000",
neverbounce.WithTestBaseURL(srv.URL),
neverbounce.WithHTTPClient(srv.Client()),
)
if err != nil {
fmt.Println("config:", err)
return
}
st, err := client.WaitForJob(context.Background(), neverbounce.WaitForJobRequest{
JobID: 4242,
Interval: 10 * time.Second, // the provider suggests 5 to 10 seconds for lists under 50,000
MaxWait: 2 * time.Hour, // manual review can take a business day: size it to the list
})
switch {
case errors.Is(err, neverbounce.ErrJobFailed):
fmt.Println("job failed:", st.FailureReason) // "" means the provider gave no reason
case errors.Is(err, neverbounce.ErrBudgetExhausted):
fmt.Println("still in progress; the job keeps running") // st is the last status read, or nil
case err != nil:
fmt.Println("wait:", err) // an undocumented state, or a failed poll: never retried
case st.State == neverbounce.JobStateComplete:
fmt.Println("complete: read the results")
case st.State == neverbounce.JobStateWaiting:
fmt.Println("parsed: a full StartJob verifies the list (billed)")
case st.State == neverbounce.JobStateWaitingAnalyzed:
fmt.Println("sample done: a full StartJob verifies the list (billed)")
if st.BounceEstimate != nil {
fmt.Printf("estimated bounce rate: %.1f%%\n", *st.BounceEstimate)
}
}
}
Output: sample done: a full StartJob verifies the list (billed) estimated bounce rate: 12.5%
type CreateJobRequest ΒΆ
type CreateJobRequest struct {
// Supplied is a list sent in the request body. The whole encoded body,
// the API key included, must fit MaxJobRequestBytes.
Supplied SuppliedList
// RemoteURL is a list the provider fetches itself (input_location
// "remote_url"): a line-separated list of addresses or a CSV file. It must
// be an absolute URL of at most 8192 bytes; any scheme the provider
// supports, and credentials in the URL, are allowed. The SDK never fetches
// it and never prints it.
RemoteURL string
// Filename is the job's name in the NeverBounce dashboard: at most 255
// bytes, sent when non-empty. A unique value is the way to find a job
// whose creation timed out, because the SDK cannot learn its ID then.
Filename string
// AutoParse starts parsing the list right after creation. When false, call
// ParseJob.
AutoParse bool
// AutoStart starts the full verification right after parsing, which
// DEDUCTS CREDITS for the provider's billable count without any review
// on your side. Leave it false to inspect JobStatus Totals.Billable and
// call StartJob deliberately.
AutoStart bool
// RunSample runs a free sample verification that estimates the list's
// bounce rate instead of verifying it (the job then reaches
// JobStateWaitingAnalyzed).
RunSample bool
// AllowManualReview lets the provider hold the job for manual review,
// which may take up to one business day (JobStateUnderReview).
AllowManualReview bool
// LeverageHistoricalData, when non-nil, is sent as
// request_meta_data.leverage_historical_data; false asks for real-time
// verification only. nil is not sent (the provider's default is true).
LeverageHistoricalData *bool
// CallbackURL is an optional http or https URL of at most 2048 bytes that
// the provider sends job events to. It may carry basic-auth credentials;
// the SDK never prints it. The provider documents no signing of these
// events.
CallbackURL string
// CallbackHeaders are optional headers the provider sends with each event,
// such as an authorization token: at most 32, names RFC 9110 tokens of up
// to 128 bytes, unique ignoring case, values up to 1024 bytes without
// control characters. They require CallbackURL. Errors and String never
// include a header name or value.
CallbackHeaders map[string]string
}
CreateJobRequest is one jobs/create call. Set exactly one of Supplied and RemoteURL. Every boolean is always sent, false included, so a provider default can never start a billed job unseen. The request is read only while CreateJob encodes it, before any I/O, and is never kept or modified; changing its slices or maps while the call runs is a data race.
func (CreateJobRequest) Format ΒΆ
func (r CreateJobRequest) Format(f fmt.State, verb rune)
Format prints the same text as String for every fmt verb (quoted for %q), so that no verb, %d and %t included, reaches the rows, URLs, filename or callback headers by reflection. fmt cannot call it for %p on a value, nor for a request held in an unexported struct field: keep requests out of formatted output there.
func (CreateJobRequest) GoString ΒΆ
func (r CreateJobRequest) GoString() string
GoString returns the same text as String, so that %#v prints the shape only.
func (CreateJobRequest) String ΒΆ
func (r CreateJobRequest) String() string
String describes the request's shape only, such as "neverbounce.CreateJobRequest{input: supplied, columns: 2, rows: 3, ...}": counts and set or unset, never rows, URLs, the filename or header values, which may hold contact data or third-party credentials.
type CreateJobResult ΒΆ
type CreateJobResult struct {
// JobID is the new job's handle.
JobID JobID `json:"job_id"`
// ExecutionTime is the provider's execution_time, when it is an integer of
// at least 0. Its units are undocumented.
ExecutionTime *int64 `json:"execution_time,omitempty"`
}
CreateJobResult is the provider's answer to jobs/create.
type CreditsInfo ΒΆ
type CreditsInfo struct {
PaidCreditsUsed *int64 `json:"paid_credits_used,omitempty"`
FreeCreditsUsed *int64 `json:"free_credits_used,omitempty"`
PaidCreditsRemaining *int64 `json:"paid_credits_remaining,omitempty"`
FreeCreditsRemaining *int64 `json:"free_credits_remaining,omitempty"`
}
CreditsInfo is the account's credit counters ("credits_info"), as the provider reported them with this answer. A nil field was not reported; a pointer to 0 was reported as zero. The SDK does not interpret them.
type DownloadColumns ΒΆ
type DownloadColumns struct {
BadSyntax *bool // bad_syntax: a yes/no column
FreeEmailHost *bool // free_email_host: a yes/no column
RoleAccount *bool // role_account: a yes/no column
Addr *bool // addr: the address part before any alias
Alias *bool // alias
Host *bool // host
Subdomain *bool // subdomain
Domain *bool // domain
TLD *bool // tld
FQDN *bool // fqdn
Network *bool // network: the FQDN of the primary MX record
HasDNSInfo *bool // has_dns_info: a yes/no column
HasMailServer *bool // has_mail_server: a yes/no column
MailServerReachable *bool // mail_server_reachable: a yes/no column
EmailStatusInt *bool // email_status_int: the result as 0 to 4; the mapping is not documented
EmailStatus *bool // email_status: the result as text (on by default)
}
DownloadColumns appends columns to a download. A nil field is not sent, leaving the provider's default; a non-nil one is sent as a JSON boolean.
type DownloadJobRequest ΒΆ
type DownloadJobRequest struct {
// JobID is the job whose results to download.
JobID JobID
// Segments selects records.
Segments DownloadSegments
// Append adds columns.
Append DownloadColumns
// BinaryFormat spells yes/no columns. "" is not sent.
BinaryFormat BinaryFormat
// LineFeed is the line ending. "" is not sent (the provider's default is
// "\n\r"; see LineFeed).
LineFeed LineFeed
}
DownloadJobRequest is one jobs/download call.
type DownloadSegments ΒΆ
type DownloadSegments struct {
// Valids, Invalids, Catchalls, Unknowns and Disposables include or exclude
// the records with each result (the provider includes all five by
// default).
Valids *bool
Invalids *bool
Catchalls *bool
Unknowns *bool
Disposables *bool
// IncludeDuplicates includes every instance of a duplicated record (off by
// default).
IncludeDuplicates *bool
// OnlyDuplicates returns only the duplicated records, overriding the
// other segment options.
OnlyDuplicates *bool
// OnlyBadSyntax returns only the records with bad syntax, overriding the
// other segment options.
OnlyBadSyntax *bool
}
DownloadSegments selects which records a download holds. A nil field is not sent, leaving the provider's default; a non-nil one is sent as a JSON boolean.
type FailureKind ΒΆ
type FailureKind string
FailureKind classifies a failed call. Each kind matches one target with errors.Is (a sentinel of this package, context.Canceled or context.DeadlineExceeded), except FailureTimeout, which matches both ErrTimeout and context.DeadlineExceeded. The values are short, fixed and free of personal data, so they are safe to use as metric labels.
const ( FailureUnauthorized FailureKind = "unauthorized" // FailureRateLimited matches ErrRateLimited. FailureRateLimited FailureKind = "rate_limited" FailureUnavailable FailureKind = "unavailable" // FailureRejected matches ErrRejected. FailureRejected FailureKind = "rejected" // FailureUpstream matches ErrUpstream. FailureUpstream FailureKind = "upstream" // FailureUnexpectedResponse matches ErrUnexpectedResponse. FailureUnexpectedResponse FailureKind = "unexpected_response" // FailureMalformedResponse matches ErrMalformedResponse. FailureMalformedResponse FailureKind = "malformed_response" // FailureResponseTooLarge matches ErrResponseTooLarge. FailureResponseTooLarge FailureKind = "response_too_large" // FailureTransport matches ErrTransport. FailureTransport FailureKind = "transport" // FailureTimeout matches ErrTimeout, and also context.DeadlineExceeded. FailureTimeout FailureKind = "timeout" // FailureCanceled means the caller's context was canceled. It matches // context.Canceled. FailureCanceled FailureKind = "canceled" // FailureDeadlineExceeded means the caller's context deadline expired. It // matches context.DeadlineExceeded, but not ErrTimeout. FailureDeadlineExceeded FailureKind = "deadline_exceeded" // FailureWriteFailed matches ErrWriteFailed. FailureWriteFailed FailureKind = "write_failed" // FailureJobFailed matches ErrJobFailed. FailureJobFailed FailureKind = "job_failed" // FailureUnknownJobState matches ErrUnknownJobState. FailureUnknownJobState FailureKind = "unknown_job_state" // FailureBudgetExhausted matches ErrBudgetExhausted. FailureBudgetExhausted FailureKind = "budget_exhausted" )
Failure kinds.
type Flag ΒΆ
type Flag string
Flag is one provider observation about an address or its domain. The set is open: a flag the provider adds later is kept as sent when it has the token shape Result describes, and Known reports false for it. v4.2 spells academic_host; the v4.1 spelling "acedemic_host" is kept verbatim if it ever appears, never normalized.
const ( FlagHasDNS Flag = "has_dns" FlagHasDNSMX Flag = "has_dns_mx" FlagBadSyntax Flag = "bad_syntax" FlagFreeEmailHost Flag = "free_email_host" FlagProfanity Flag = "profanity" FlagRoleAccount Flag = "role_account" FlagDisposableEmail Flag = "disposable_email" FlagGovernmentHost Flag = "government_host" FlagAcademicHost Flag = "academic_host" FlagMilitaryHost Flag = "military_host" FlagInternationalHost Flag = "international_host" FlagSquatterHost Flag = "squatter_host" FlagSpellingMistake Flag = "spelling_mistake" FlagBadDNS Flag = "bad_dns" FlagTemporaryDNSError Flag = "temporary_dns_error" FlagConnectFails Flag = "connect_fails" FlagAcceptsAll Flag = "accepts_all" FlagContainsAlias Flag = "contains_alias" FlagContainsSubdomain Flag = "contains_subdomain" FlagSMTPConnectable Flag = "smtp_connectable" FlagSpamtrapNetwork Flag = "spamtrap_network" FlagHistoricalResponse Flag = "historical_response" )
Documented v4.2 flags, in the provider's order.
type Flags ΒΆ
type Flags []Flag
Flags is the provider's flag list, in the provider's order, with duplicates kept. An empty list is nil.
type JobFailureReason ΒΆ
type JobFailureReason string
JobFailureReason is a failed job's "failure_reason". The set is open. "" means the provider sent null or nothing; on a failed job that means the provider gave no reason.
const ( JobFailureUnknownFileEncoding JobFailureReason = "unknown_file_encoding" JobFailureEmptyFile JobFailureReason = "empty_file" JobFailureFileTooLarge JobFailureReason = "file_too_large" JobFailureFileCorrupt JobFailureReason = "file_corrupt" )
Documented failure reasons.
func (JobFailureReason) Known ΒΆ
func (r JobFailureReason) Known() bool
Known reports whether r is one of the four documented reasons.
type JobID ΒΆ
type JobID int64
JobID is the provider's integer handle for a bulk job. Valid IDs are greater than 0. It marshals as a JSON number.
type JobResultPagesRequest ΒΆ
type JobResultPagesRequest struct {
// JobID is the job whose results to read.
JobID JobID
// StartPage is the first page to read: 0 means 1.
StartPage int
// ItemsPerPage is the page size, from 1 to MaxItemsPerPage: 0 means
// DefaultPageSize. It is always sent.
ItemsPerPage int
// MaxPages is the required page budget: the most jobs/results calls one
// walk makes, from 1 to 100,000.
MaxPages int
}
JobResultPagesRequest is one JobResultPages walk.
type JobResultsPage ΒΆ
type JobResultsPage struct {
// Page is the page the SDK requested, or 1 (the provider's default) when
// JobResultsRequest.Page was 0. The provider's own echo of the request
// ("query", whose documented example says page 0) is never decoded. This
// field is the SDK's: the provider's answer has no top-level "page".
Page int `json:"page"`
// TotalResults is the provider's total_results.
TotalResults int64 `json:"total_results"`
// TotalPages is the provider's total_pages.
TotalPages int64 `json:"total_pages"`
// Results are the page's rows in the provider's order: none dropped,
// reordered or deduplicated. The provider may return a list's header row
// as a record, and duplicates, so correlate rows by a column of your own,
// never by position. nil when the page is empty.
Results []ResultRow `json:"results,omitempty"`
// ExecutionTime is the provider's execution_time, when it is an integer of
// at least 0. Its units are undocumented.
ExecutionTime *int64 `json:"execution_time,omitempty"`
}
JobResultsPage is one page of a job's results.
It survives a JSON round trip through encoding/json unchanged, under the provider's snake_case names. Unmarshaling a raw provider body into it skips every check the SDK makes.
func (*JobResultsPage) More ΒΆ
func (p *JobResultsPage) More() bool
More reports whether a later page exists: int64(p.Page) < p.TotalPages. It is false for a nil page.
type JobResultsRequest ΒΆ
type JobResultsRequest struct {
// JobID is the job whose results to read.
JobID JobID
// Page is the page to read, from 1. 0 means not sent (the provider's
// default is 1).
Page int
// ItemsPerPage is the page size, from 1 to MaxItemsPerPage. 0 means not
// sent (the provider's default is 10).
ItemsPerPage int
}
JobResultsRequest is one jobs/results call.
type JobState ΒΆ
type JobState string
JobState is a job's "job_status". The set is open: a state the provider adds later is kept as sent when it has the token shape Result describes, and Known reports false for it (and InProgress, NeedsAction and Terminal all report false).
const ( // JobStateUploading means the list is being uploaded. JobStateUploading JobState = "uploading" // JobStateParsing means the provider is reading the list for addresses and // duplicates. JobStateParsing JobState = "parsing" // JobStateWaiting means the job is parsed and waits to be started: call // StartJob (a full start is billed). JobStateWaiting JobState = "waiting" // JobStateWaitingAnalyzed means a sample has finished and the job waits // for further action: a full StartJob verifies it (billed). JobStateWaitingAnalyzed JobState = "waiting_analyzed" // JobStateQueued means the job waits for capacity, the provider's or the // account's concurrent-job limit. JobStateQueued JobState = "queued" // JobStateRunning means a sample or full verification is running. JobStateRunning JobState = "running" // JobStateUnderReview means the job is in the provider's manual review, // which may take up to one business day. JobStateUnderReview JobState = "under_review" // JobStateComplete means the results are ready. JobStateComplete JobState = "complete" // JobStateFailed means the job failed; see JobStatus.FailureReason. JobStateFailed JobState = "failed" )
Documented job states.
func (JobState) InProgress ΒΆ
InProgress reports whether the provider is still working on the job without any action from you: uploading, parsing, queued, running or under_review.
func (JobState) NeedsAction ΒΆ
NeedsAction reports whether the job waits for you: waiting (a start is needed) or waiting_analyzed (a sample is done; a full start is needed).
type JobStatus ΒΆ
type JobStatus struct {
// ID is the job's handle. The SDK checks that it is the job requested.
ID JobID `json:"id"`
// State is the job's job_status: what can be done with the job now.
State JobState `json:"job_status"`
// Filename is the job's name in the dashboard.
Filename string `json:"filename,omitempty"`
// CreatedAt, StartedAt and FinishedAt are the provider's timestamps as
// text, such as "2026-10-15 14:52:27". Their time zone is undocumented, so
// the SDK never parses them. "" means not reported.
CreatedAt string `json:"created_at,omitempty"`
StartedAt string `json:"started_at,omitempty"`
FinishedAt string `json:"finished_at,omitempty"`
// FailureReason is the provider's reason for a failed job, or "".
FailureReason JobFailureReason `json:"failure_reason,omitempty"`
// Totals are the job's counters.
Totals JobTotals `json:"total,omitzero"`
// BounceEstimate is the provider's estimated bounce rate, from 0 to 100,
// when reported.
BounceEstimate *float64 `json:"bounce_estimate,omitempty"`
// PercentComplete is the job's progress, from 0 to 100, when reported. It
// is progress only: completion is State, never this value.
PercentComplete *float64 `json:"percent_complete,omitempty"`
// ExecutionTime is the provider's execution_time, when it is an integer of
// at least 0. Its units are undocumented.
ExecutionTime *int64 `json:"execution_time,omitempty"`
}
JobStatus is the provider's jobs/status answer. Only the v4.2 shape, with its nested "total", is modeled.
It survives a JSON round trip through encoding/json unchanged, under the provider's snake_case names. Unmarshaling a raw provider body into it skips every check the SDK makes.
type JobStatusRequest ΒΆ
type JobStatusRequest struct {
// JobID is the job to read.
JobID JobID
}
JobStatusRequest is one jobs/status call.
type JobTotals ΒΆ
type JobTotals struct {
// Records is the number of rows the provider found in the list.
Records *int64 `json:"records,omitempty"`
// Billable is the number of credits a full verification of this job
// consumes: the provider's count of unique, syntactically valid
// addresses. The SDK never estimates or deduplicates on its own.
Billable *int64 `json:"billable,omitempty"`
// Processed is the number of addresses processed so far.
Processed *int64 `json:"processed,omitempty"`
// Valid, Invalid, Catchall, Disposable and Unknown count each result.
Valid *int64 `json:"valid,omitempty"`
Invalid *int64 `json:"invalid,omitempty"`
Catchall *int64 `json:"catchall,omitempty"`
Disposable *int64 `json:"disposable,omitempty"`
Unknown *int64 `json:"unknown,omitempty"`
// Duplicates counts every instance of a duplicated record, not unique
// duplicates.
Duplicates *int64 `json:"duplicates,omitempty"`
// BadSyntax counts records with no data that looks like an address.
BadSyntax *int64 `json:"bad_syntax,omitempty"`
}
JobTotals is a job's "total" counters, which the provider updates periodically while the job runs. A nil field was not reported; a pointer to 0 was reported as zero.
type LineFeed ΒΆ
type LineFeed string
LineFeed is a download's line ending ("line_feed_type").
The provider's default is LineFeedLFCR, "\n\r", which encoding/csv reads as a stray "\r" at the start of every following record: set LineFeedCRLF or LineFeedLF when the file will be parsed.
type Operation ΒΆ
type Operation string
Operation names the provider operation a CallError concerns. Its value is the operation's path under https://api.neverbounce.com/v4.2/.
const ( // OpCheckEmail is single/check (CheckEmail). OpCheckEmail Operation = "single/check" // OpCreateJob is jobs/create (CreateJob). OpCreateJob Operation = "jobs/create" // OpParseJob is jobs/parse (ParseJob). OpParseJob Operation = "jobs/parse" // OpStartJob is jobs/start (StartJob). OpStartJob Operation = "jobs/start" // OpJobStatus is jobs/status (JobStatus and WaitForJob). OpJobStatus Operation = "jobs/status" // OpJobResults is jobs/results (JobResults and JobResultPages). OpJobResults Operation = "jobs/results" // OpDownloadJob is jobs/download (DownloadJob). OpDownloadJob Operation = "jobs/download" )
Operations.
type Option ΒΆ
type Option func(*options)
Option configures NewClient. Options only record their argument: NewClient validates the result. A nil Option is skipped, and when an option is given more than once the last one wins.
func WithDownloadTimeout ΒΆ
WithDownloadTimeout bounds a whole DownloadJob call, streaming included. The default is DefaultDownloadTimeout (30 minutes); d must be greater than 0 and at most 12 hours.
func WithHTTPClient ΒΆ
WithHTTPClient makes calls through a copy of hc. The copy refuses redirects (its CheckRedirect returns http.ErrUseLastResponse), has no cookie jar, keeps hc.Timeout, and wraps hc's transport, without modifying it, so that every redirect comes back as a plain response with its Location removed and is never followed. A nil transport means http.DefaultTransport. hc itself is never modified. hc.Timeout applies to every call, DownloadJob included: leave it 0 when downloading large lists.
The transport is trusted: it sees the API key and the email addresses in every request body, and it may retry on its own, which the SDK cannot prevent. A nil hc is rejected.
func WithMaxDownloadBytes ΒΆ
WithMaxDownloadBytes limits the bytes DownloadJob copies to its writer. The default is DefaultMaxDownloadBytes (1 GiB); n must be from 1 byte to 64 GiB. A longer download fails with ErrResponseTooLarge after exactly n bytes.
func WithMaxResponseBytes ΒΆ
WithMaxResponseBytes limits a JSON response body, counted after any transport decompression. The default is DefaultMaxResponseBytes (8 MiB); n must be from 1 byte to 64 MiB. Every operation except jobs/results is also capped at 1 MiB. A larger HTTP 200 body fails with ErrResponseTooLarge, after the provider may already have processed the call.
func WithProviderDiagnostics ΒΆ
func WithProviderDiagnostics() Option
WithProviderDiagnostics keeps the provider's "message" on errors, reachable only through (*CallError).Diagnostics, cut to 1 KiB and with the API key replaced by "[redacted]". It is off by default, because errors are routinely logged and passed on, and provider text may echo request data such as an email address.
func WithTestBaseURL ΒΆ
WithTestBaseURL sends calls to a local test server instead of the provider. It exists for tests built on httptest.NewTLSServer, together with WithHTTPClient(srv.Client()). The SDK appends /v4.2/<operation> to it.
The URL must use https and have a host that is a canonical IPv4 address in 127.0.0.0/8 or exactly [::1], with an optional port and no userinfo, query, fragment or path (a lone trailing "/" is allowed). Names such as "localhost" are rejected, because they resolve through the system resolver. Errors never quote the URL. There is no option for any other base URL, so the API key reaches only the provider or loopback.
func WithTimeout ΒΆ
WithTimeout bounds each JSON call, including reading the whole response body. The default is DefaultTimeout (60 seconds); d must be greater than 0 and at most 10 minutes. The caller's context deadline applies as well. It does not apply to DownloadJob (see WithDownloadTimeout).
type ParseJobRequest ΒΆ
type ParseJobRequest struct {
// JobID is the job to parse, created without AutoParse.
JobID JobID
// AutoStart starts the full verification right after parsing, which
// DEDUCTS CREDITS for the provider's billable count. It is always sent,
// false included.
AutoStart bool
}
ParseJobRequest is one jobs/parse call.
type ParseJobResult ΒΆ
type ParseJobResult struct {
// QueueID is the provider's queue_id, kept as opaque metadata when it is a
// string of 1 to 128 visible ASCII bytes, and "" otherwise.
QueueID string `json:"queue_id,omitempty"`
// ExecutionTime is the provider's execution_time, when it is an integer of
// at least 0. Its units are undocumented.
ExecutionTime *int64 `json:"execution_time,omitempty"`
}
ParseJobResult is the provider's answer to jobs/parse.
type ProviderDiagnostics ΒΆ
type ProviderDiagnostics struct {
// Message is the envelope's "message", cut to at most 1 KiB on a UTF-8
// boundary, with every occurrence of the API key replaced by
// "[redacted]". It may echo request data, such as an email address.
Message string
}
ProviderDiagnostics holds provider text about a failed call. It is empty unless the Client was created with WithProviderDiagnostics.
type Result ΒΆ
type Result string
Result is the provider's verdict on one address. The set is open: a value the provider adds later is kept as sent when it has the documented token shape (lowercase letters, digits and "_", up to 64 bytes), and Known reports false for it; any other value fails the call as unexpected_response. There is deliberately no "safe to send" helper: what to do with each verdict is the caller's policy.
const ( // ResultValid means the provider verified the address as real. ResultValid Result = "valid" // ResultInvalid means the provider verified the address as not valid. ResultInvalid Result = "invalid" // ResultDisposable means a temporary, disposable address. ResultDisposable Result = "disposable" // ResultCatchall means the domain accepts all mail (accept-all), so the // address itself could not be verified. It is not a "safe" verdict. ResultCatchall Result = "catchall" // ResultUnknown means the provider could not reach the server. It is a // successful answer, never an error, and the check was still billed. ResultUnknown Result = "unknown" )
Documented results.
type ResultRow ΒΆ
type ResultRow struct {
// Data is the provider's "data": the record as you submitted it, as a JSON
// object (keyed by your column names) or array. It is compacted and
// escaped as encoding/json marshals a json.RawMessage, at most 64 KiB,
// and never aliases the response. Values may come back as strings even
// when submitted as numbers. nil when absent or null.
Data json.RawMessage `json:"data,omitempty"`
// Verification is the provider's verdict on the record.
Verification RowVerification `json:"verification"`
}
ResultRow is one record of a job's results.
type RowVerification ΒΆ
type RowVerification struct {
// Result is the verdict. ResultUnknown is a successful answer.
Result Result `json:"result"`
// Flags are the provider's observations, in its order. nil when none.
Flags Flags `json:"flags,omitempty"`
// SuggestedCorrection is the provider's soft suggestion for a likely typo,
// or "". The SDK never applies it.
SuggestedCorrection string `json:"suggested_correction,omitempty"`
// AddressInfo is the provider's parse of the address, when reported.
AddressInfo *AddressInfo `json:"address_info,omitempty"`
}
RowVerification is a record's "verification": the same verdict single/check returns, without the credit counters.
type StartJobRequest ΒΆ
type StartJobRequest struct {
// JobID is the parsed job to start. After a sample reaches
// JobStateWaitingAnalyzed, the full start uses the same JobID.
JobID JobID
// RunSample runs a free sample verification instead. When false, which is
// always sent explicitly, this is a FULL start: it deducts credits and the
// job cannot be stopped or restarted.
RunSample bool
}
StartJobRequest is one jobs/start call.
type StartJobResult ΒΆ
type StartJobResult struct {
// QueueID is the provider's queue_id, kept as opaque metadata when it is a
// string of 1 to 128 visible ASCII bytes, and "" otherwise.
QueueID string `json:"queue_id,omitempty"`
// ExecutionTime is the provider's execution_time, when it is an integer of
// at least 0. Its units are undocumented.
ExecutionTime *int64 `json:"execution_time,omitempty"`
}
StartJobResult is the provider's answer to jobs/start.
type SuppliedList ΒΆ
type SuppliedList struct {
// Columns are the column names: 1 to 128 of them, each 1 to 256 bytes of
// valid UTF-8 without control characters, unique ignoring ASCII case.
Columns []string
// Rows are the records: at least one, each with exactly len(Columns)
// values in Columns order. Each value is sent verbatim as a JSON string:
// at most 4096 bytes of valid UTF-8 without control characters (so no
// embedded line breaks); empty values are allowed.
Rows [][]string
}
SuppliedList is a list sent in the jobs/create request body (input_location "supplied") as a JSON array of objects: each row becomes one object whose keys are Columns, in order, which the provider uses as the list's column headers. It maps one to one from a CSV header row and its records.
The SDK requires no particular column: the provider documents none, and its examples name the address column "email". Headerless (array) rows are not offered.
func EmailList ΒΆ
func EmailList(emails ...string) SuppliedList
EmailList returns a SuppliedList with the single column "email" (the name the provider's examples use) and one row per address, in order. It copies emails, so later changes to the slice do not affect the list.
type ValidationError ΒΆ
ValidationError describes a local validation failure: nothing was sent. Err is ErrInvalidConfig or ErrInvalidRequest. Field names the argument, option or request field as a Go path, such as "Supplied.Rows[17][1]" or "Timeout", and Reason is a short fixed code, such as "control_character". Neither ever contains the rejected value.
func (*ValidationError) Error ΒΆ
func (e *ValidationError) Error() string
Error returns the sentinel's message followed by the field and the reason, such as "neverbounce: invalid request: Email: control_character".
func (*ValidationError) Unwrap ΒΆ
func (e *ValidationError) Unwrap() error
Unwrap returns the sentinel, ErrInvalidConfig or ErrInvalidRequest.
type WaitForJobRequest ΒΆ
type WaitForJobRequest struct {
// JobID is the job to watch.
JobID JobID
// Interval is the pause between the end of one poll and the start of the
// next: 0 means DefaultWaitInterval, otherwise 1 second to 10 minutes.
// The provider suggests polling every 5 to 10 seconds for lists under
// 50,000 addresses, and less often for larger lists.
Interval time.Duration
// MaxWait is the required elapsed-time budget, more than 0 and at most 72
// hours. Manual review can take a business day: size it accordingly.
MaxWait time.Duration
}
WaitForJobRequest is one WaitForJob call.
Source Files
ΒΆ
Directories
ΒΆ
| Path | Synopsis |
|---|---|
|
Command examples shows the go-neverbounce SDK end to end, offline: a local TLS server plays a synthetic NeverBounce, so the demo needs no API key, makes no network call and costs nothing.
|
Command examples shows the go-neverbounce SDK end to end, offline: a local TLS server plays a synthetic NeverBounce, so the demo needs no API key, makes no network call and costs nothing. |
|
quickstart
command
Command quickstart verifies one address against the live NeverBounce API.
|
Command quickstart verifies one address against the live NeverBounce API. |
|
internal
|
|
|
testutil
Package testutil holds the test plumbing go-neverbounce's tests share: testdata fixtures, HTTP fakes, a recording TLS server for HTTP/1.1 and HTTP/2, a scripted transport, writer fakes for streaming downloads, formatting-leak assertions, a token-walk JSON oracle, race-aware allocation guards, and the value-free shape printer the live probe reports with.
|
Package testutil holds the test plumbing go-neverbounce's tests share: testdata fixtures, HTTP fakes, a recording TLS server for HTTP/1.1 and HTTP/2, a scripted transport, writer fakes for streaming downloads, formatting-leak assertions, a token-walk JSON oracle, race-aware allocation guards, and the value-free shape printer the live probe reports with. |
