neverbounce

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 25 Imported by: 0

README ΒΆ

πŸ“¬Β Β go-neverbounce

A small, typed Go SDK for the NeverBounce API v4.2: single and bulk email verification.


Release Go Version License


CI / CD Β Β  Build Last Commit Β Β Β Β  Quality Β Β  Coverage
Security Β Β  Scorecard Security Β Β Β Β  Community Β Β  Contributors Bitcoin


Project Navigation
πŸš€Β Installation 🏁 QuickΒ Start πŸ’‘Β Usage βš™οΈΒ Behavior πŸ“šΒ Documentation
πŸ§ͺΒ ExamplesΒ &Β Tests ⚑ Benchmarks πŸ› οΈΒ CodeΒ Standards πŸ€–Β AIΒ Usage 🀝 Contributing

go-neverbounce calls NeverBounce's API v4.2 to verify email addresses: one address at a time with single/check, or whole lists through NeverBounce's bulk jobs (create, parse, start, status, results and download). Use it when a Go service needs to know whether an address is deliverable and has to stay in control of every billable call.

  • One attempt per call. No retries, redirects, replays, hedging or hidden pagination: the SDK never repeats a request on its own, and Go's HTTP clients cannot resend one either.
  • Typed results that keep NeverBounce's meaning. unknown is an answer, not an error; an absent count is nil, not 0; undocumented verdicts, flags and job states are kept as sent when they have the documented token shape.
  • Nothing paid happens implicitly. Every billed or state-changing step (a check, creating, parsing or starting a job) is a method you call. The helpers only read: WaitForJob polls status, and JobResultPages reads pages, each within a budget you set.
  • Bounded and streaming. Every call has a timeout and a size limit; result CSVs stream straight to your io.Writer, byte for byte.
  • Private by construction. Errors and printed clients never contain the API key, email addresses, URLs, bodies or NeverBounce's messages.
  • Zero runtime dependencies: the standard library only.

Version 1 covers single verification and the bulk-jobs workflow of API v4.2; see what is not covered.


πŸ“¦ Installation

go-neverbounce requires a supported release of Go (Go 1.26 or newer).

go get github.com/mrz1836/go-neverbounce

The library has zero third-party runtime dependencies: it uses only the standard library. testify is used only by the tests and their internal helper package.


Credentials

You need a NeverBounce v4 API key (it starts with secret_), created in the NeverBounce dashboard; v3 credentials are refused with auth_failure. go-neverbounce never reads an environment variable or a configuration file for it: your code passes the key to neverbounce.NewClient, from wherever it keeps secrets. The key travels only in the JSON body of each request, never in a URL or a header.

NeverBounce documents no sandbox and no free test addresses: every CheckEmail call is billed, and so is every full job start. Try the SDK offline first with go run ./examples.


🏁 Quick Start

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mrz1836/go-neverbounce"
)

func main() {
	// The application chooses where the key comes from; the SDK reads no environment.
	client, err := neverbounce.NewClient(os.Getenv("NEVERBOUNCE_API_KEY"))
	if err != nil {
		log.Fatal(err) // ErrInvalidConfig: no call was made
	}

	// One billable call (1 credit), whatever the result.
	res, err := client.CheckEmail(context.Background(), neverbounce.CheckEmailRequest{
		Email:       "avery.example@example.com",
		AddressInfo: true,
	})
	if err != nil {
		log.Fatal(err) // the check may already be billed: do not resend blindly
	}
	fmt.Println(res.Result, res.Flags)
}

Illustrative output (the values are NeverBounce's):

valid [has_dns has_dns_mx smtp_connectable]

Next steps

πŸ’‘ Usage

Set up once

Create one Client per API key and share it: it is immutable and safe for concurrent use.

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
}
Option Default Accepted values
WithTimeout(d) 60s (DefaultTimeout) More than 0, at most 10 minutes. Each JSON call, including the whole body read. An earlier deadline on the call's context wins.
WithMaxResponseBytes(n) 8 MiB (DefaultMaxResponseBytes) 1 byte to 64 MiB. Every operation except jobs/results is also capped at 1 MiB.
WithDownloadTimeout(d) 30 minutes (DefaultDownloadTimeout) More than 0, at most 12 hours. A whole DownloadJob, streaming included.
WithMaxDownloadBytes(n) 1 GiB (DefaultMaxDownloadBytes) 1 byte to 64 GiB: the bytes DownloadJob writes.
WithHTTPClient(hc) a transport the SDK builds A non-nil *http.Client; see the transport.
WithTestBaseURL(url) https://api.neverbounce.com Tests only: https on 127.0.0.0/8 or [::1], an optional port, and no path, query, fragment or userinfo.
WithProviderDiagnostics() off Keeps NeverBounce's message on errors, behind (*CallError).Diagnostics, with the key scrubbed.

Nil options are skipped and the last option of each kind wins. NewClient validates the key (1 to 256 bytes of visible ASCII, without " or \) and every option before returning, and performs no I/O. Its errors name the argument or option, never the rejected value.

Holding many keys? Without WithHTTPClient, each Client owns a connection pool that cannot be closed (idle connections close on their own after 90 seconds). Pass the same *http.Client to every Client so that they share one pool.


Check one email

CheckEmail verifies one address and costs one credit per call, duplicates and syntactically bad addresses included.

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)
}
Request field Sent as Meaning
Email email Sent verbatim: never trimmed, normalized or checked against an RFC. 1 to 1024 bytes of UTF-8 without control characters, and not only whitespace. A malformed address is a legitimate (billed) input.
AddressInfo address_info Ask for NeverBounce's parse of the address. Always sent.
CreditsInfo credits_info Ask for the account's credit counters. Always sent.
Timeout timeout (seconds) NeverBounce's own verification timeout; it then answers unknown. 0 is not sent. Whole seconds, 1s to 300s, and at least 10 seconds below WithTimeout.
LeverageHistoricalData request_meta_data.leverage_historical_data false asks for real-time verification only; nil is not sent.
Result Meaning
ResultValid Verified as a real address.
ResultInvalid Verified as not valid.
ResultDisposable A temporary, disposable address.
ResultCatchall The domain accepts all mail, so the address itself could not be verified.
ResultUnknown The server could not be reached. A successful (and billed) answer, not an error.

Flags lists NeverBounce's observations, such as FlagRoleAccount, FlagFreeEmailHost or FlagHistoricalResponse, in NeverBounce's order; the SDK defines all 22 documented flags. Good to know:

  • unknown is an answer. The SDK never re-checks it on its own; whether to retry later is your policy, and a retry is another credit.
  • SuggestedCorrection is a suggestion. The SDK never applies it or checks the suggested address.
  • catchall is not "safe". There is deliberately no IsValid or "deliverable" helper: what to do with each verdict is your decision.
  • Unknown values are kept as sent when they have the documented token shape (lowercase letters, digits and _, up to 64 bytes); anything else fails as ErrUnexpectedResponse. Result, Flag and JobState have Known(); the v4.1 spelling acedemic_host would come back verbatim, never normalized.
  • A verdict is an observation, not consent, identity, ownership or a promise of future deliverability.

Verify a list

NeverBounce verifies lists as jobs. A job moves through these states:

create ──► parsing ──► waiting ──► StartJob ──► queued / running ──► complete
              (AutoParse or ParseJob)   (billed here)                    or failed
JobState Meaning What you do
JobStateUploading, JobStateParsing NeverBounce is reading the list. Wait.
JobStateWaiting Parsed; Totals.Billable says what a full start costs. Inspect, then call StartJob.
JobStateWaitingAnalyzed A free sample finished (RunSample); BounceEstimate holds the estimate when NeverBounce reports it. Call StartJob for the full run, on the same JobID.
JobStateQueued, JobStateRunning Waiting for capacity, or verifying. Wait.
JobStateUnderReview In NeverBounce's manual review (AllowManualReview), up to one business day. Wait.
JobStateComplete Results are ready. Read them or download them.
JobStateFailed The job failed; FailureReason says why when NeverBounce knows. Fix the list and create a new job.

The deliberate flow creates a job that only parses, inspects the billable count, and starts it explicitly:

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)

Billing.

  • AutoStart on CreateJob or ParseJob starts the job and deducts the credits as soon as parsing ends, without your review. The SDK always sends it explicitly, false included.
  • A full start (StartJob with RunSample: false) deducts credits for NeverBounce's billable count (unique, syntactically valid addresses) and cannot be stopped or restarted.
  • A sample (RunSample: true) is free and estimates the bounce rate.
  • After any error from CreateJob, StartJob, or ParseJob with AutoStart, a timeout included, a job may exist or may already be running: read JobStatus (or look for the job's unique Filename in the dashboard) before trying again.

Inputs and limits

A list is either supplied in the request or fetched by NeverBounce:

  • SuppliedList has Columns (1 to 128 non-blank names, unique ignoring ASCII case) and at least one of Rows (each with exactly one value per column, sent verbatim as JSON strings, up to 4096 bytes each and without control characters, so no line breaks or tabs). It maps one to one from a CSV header and its records; EmailList(addresses...) builds the common one-column case, named email as in NeverBounce's examples. NeverBounce documents no required column name.
  • RemoteURL is a list NeverBounce downloads itself (a CSV file or one address per line), over any protocol NeverBounce supports, with credentials in the URL if needed. The SDK never fetches it.

The whole encoded jobs/create request, the key included, must fit MaxJobRequestBytes: NeverBounce's "25 MB", read as 25,000,000 bytes. A larger list fails locally, before anything is sent; use RemoteURL or smaller chunks. CallbackURL and CallbackHeaders ask NeverBounce to post job events to your server; NeverBounce documents no signing for them, and the SDK does not receive them.

A request that fails any check returns a *neverbounce.ValidationError matching neverbounce.ErrInvalidRequest, naming the first check that failed by field path, such as Supplied.Rows[17][1] (or request when the whole body is too large), and never the value. No call is made.


Wait for a job

WaitForJob polls jobs/status, first immediately and then Interval (10 seconds by default) after each poll ends, within the MaxWait you must set. It never creates, parses, starts or resubmits anything, and starts no background goroutine of its own.

Observed Returns
complete, waiting, waiting_analyzed (status, nil): switch on status.State.
failed (status, err), err matching ErrJobFailed; status.FailureReason says why.
An undocumented state (status, err) matching ErrUnknownJobState: surfaced, not polled through.
uploading, parsing, queued, running, under_review Keeps polling.
MaxWait ends: no poll starts at or after it, and one still running then is cut off (last, err) matching ErrBudgetExhausted.
Your context ends (last, err) matching context.Canceled or context.DeadlineExceeded.
A status call fails (last, that error), with no retry.
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)
	}
}

It makes at most ceil(MaxWait/Interval) calls. Canceling stops the polling, never the job or its billing. NeverBounce suggests polling every 5 to 10 seconds for lists under 50,000 addresses, and less often for larger lists.


Read results

JobResults reads one page (up to MaxItemsPerPage, 1000 rows); JobResultPages walks pages with a budget. Each row's Data is your original record as raw JSON, and Column reads one value from it:

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)
}

A bounded walk, resumed where the page budget ran out:

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)
}
  • Correlate by your own column, never by position. NeverBounce may return a list's header row as a record ({"id":"id","email":"email"}), may return duplicates, and does not document the order.
  • Values may come back as strings even when you sent numbers; Column returns a number's literal text too.
  • Page is the page the SDK asked for. NeverBounce's own echo of the query (whose documented example says page 0) is never read.
  • The iterator makes one call per page, only after you consume the previous one, and stops after the last page. It refuses a page that contradicts the walk (changed totals, an empty page before the last, rows past the end, or more pages than jobs/results can number, past 2,147,483,647), and with more pages left after MaxPages it yields ErrBudgetExhausted once, with CallError.Page set to the page to resume at. A page holding more rows than requested fails as ErrUnexpectedResponse.

Download the CSV

DownloadJob streams the job's CSV to an io.Writer you own and returns the bytes written:

// 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
}
  • Nothing is written until the response is known to be a file. An HTTP error, a JSON envelope (such as a job that is not complete), a content type other than application/octet-stream or text/csv, or a declared length over the limit writes nothing.
  • The bytes are copied unchanged: no CSV parsing, no BOM, no line-ending rewrite. NeverBounce's default line ending is "\n\r", which encoding/csv reads as a stray \r at the start of each following record: set LineFeedCRLF or LineFeedLF if you parse the file.
  • The writer is yours: the SDK never closes, flushes or inspects it. On an error after streaming began, it holds a partial file of n bytes: discard it. There is no resume.
  • DownloadSegments selects records (valid, invalid, duplicates…) and DownloadColumns appends columns; a nil switch is not sent, leaving NeverBounce's default.

Errors

Every error falls into exactly one row of the error reference. Match the classes with errors.Is, and use errors.AsType[*neverbounce.CallError] for the details of a call that passed validation:

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"
}

*neverbounce.CallError carries Kind, Op, StatusCode (HTTP), APIStatus (NeverBounce's envelope status), JobID, Page, Field (a JSON path for shape failures) and BytesWritten (downloads). Its Error() holds short codes only, never values or messages, such as neverbounce: jobs/status: rate_limited (HTTP 200, throttle_triggered). NeverBounce reports most failures inside an HTTP 200 envelope; any other HTTP status decides the kind on its own.

How to tell
Nothing was sent a *ValidationError. A canceled/deadline_exceeded error with StatusCode 0 means no response arrived: the request may still have been sent and billed
NeverBounce refused unauthorized, rate_limited or rejected, with StatusCode and APIStatus
NeverBounce had a server error unavailable or upstream: the request may still have been processed
A valid "unknown" verdict err == nil && res.Result == neverbounce.ResultUnknown
The answer could not be read malformed_response, unexpected_response or response_too_large: the call may have been billed, or a job created or started
Canceled or timed out context.Canceled, ErrTimeout, context.DeadlineExceeded (check ErrTimeout first)
Bulk work stopped short ErrJobFailed, ErrUnknownJobState or ErrBudgetExhausted, with the last status or the page to resume at

Timeouts, billing and repeat calls
  • The SDK never retries, hedges, falls back, splits a list, polls or paginates on its own, and never follows a redirect. It sends each request without a rewindable body, so Go's HTTP/1.1 and HTTP/2 clients cannot resend it either.
  • A canceled or timed-out call may still be processed and billed. Cancellation stops the SDK from waiting, not NeverBounce from working.
  • CheckEmailRequest.Timeout is NeverBounce's verification timeout, not the client's: the whole request can take longer, so the SDK requires it to stay 10 seconds below WithTimeout. NeverBounce's guide suggests treating a client-side timeout as unknown.
  • NeverBounce documents no idempotency mechanism, no rate-limit headers and no numeric rate limit; the SDK sends no idempotency key.

In a net/http handler
type signupHandler struct {
	client *neverbounce.Client
}

// ServeHTTP checks the form's email field.
func (h signupHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// r.Context() ends when the visitor goes away; the application adds its
	// own deadline on top. Either may end a check the provider still bills.
	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:
		// err holds no key, address or provider text: safe to log.
		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 // the visitor went away
	}
}

Testing your application

Depend on a small interface of your own and fake it:

type EmailChecker interface {
	CheckEmail(ctx context.Context, req neverbounce.CheckEmailRequest) (*neverbounce.CheckEmailResult, error)
}
var _ EmailChecker = (*neverbounce.Client)(nil)
// 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
}

A fake can return a hand-built *neverbounce.CallError; it matches errors.Is exactly like one the SDK returns. To exercise the real SDK offline, serve synthetic responses from httptest.NewTLSServer and pass neverbounce.WithHTTPClient(srv.Client()) and neverbounce.WithTestBaseURL(srv.URL), as the examples do.


Storing results

Every result type round-trips through encoding/json unchanged (reflect.DeepEqual), under NeverBounce's snake_case names, keeping absent and zero counts apart. Unmarshaling a raw NeverBounce body into these types skips every check the SDK makes, so store what the SDK returned:

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))

βš™οΈ Behavior

The transport

Without WithHTTPClient, each Client builds its own *http.Transport with the settings of http.DefaultTransport (HTTP/2, and the standard dial, TLS and idle timeouts), plus a 64 KiB limit on response headers. Later changes to http.DefaultTransport do not reach it. Like the default transport, it takes a proxy from the HTTPS_PROXY and NO_PROXY environment variables: that is the standard library reading the environment, not the SDK. To bypass proxies, inject a client whose transport sets no Proxy.

With WithHTTPClient(hc), the SDK uses a copy of hc taken at NewClient, with redirects refused, every 3xx Location header removed, and no cookie jar. hc itself is never modified, its Timeout still applies (to downloads too), and its Transport is shared. An injected transport is trusted code: it sees the API key in every request body, and one that retries or replays requests on its own defeats the one-attempt guarantee.

Every request is a POST to https://api.neverbounce.com/v4.2/<operation> with a JSON body whose first member is key, Content-Type: application/json, Accept: application/json (*/* for downloads) and User-Agent: go-neverbounce, and never an Authorization, cookie or idempotency header. Go's transport may request gzip on its own and decompresses it; the limits apply to the decompressed bytes. A response body is always closed. A JSON body is never read more than one byte past its limit; a download may read up to 64 KiB ahead of what it writes.


Limits
Bound Value
API key 1 to 256 bytes of visible ASCII
jobs/create request, key included 25,000,000 bytes (MaxJobRequestBytes)
Any other request 64 KiB
Supplied list 1 to 128 columns of up to 256 bytes; values up to 4096 bytes
RemoteURL, CallbackURL, Filename 8192, 2048 and 255 bytes
Callback headers 32; names up to 128 bytes, values up to 1024
JSON response 8 MiB by default, up to 64 MiB; 1 MiB for every operation except jobs/results
Error response body read 64 KiB, best-effort
Response headers (SDK-built transport) 64 KiB
JSON objects and arrays / values in a response 100,000 / 1,000,000
One text field / flags per verdict / one row's data 4 KiB / 64 / 64 KiB
Rows per results page ItemsPerPage, or 1000 when not sent
Download 1 GiB by default, up to 64 GiB; 30 minutes by default, up to 12 hours
WaitForJob Interval 1 second to 10 minutes; MaxWait up to 72 hours
JobResultPages MaxPages 1 to 100,000; 100 rows per page by default

A field over its bound fails the call as ErrResponseTooLarge: the SDK never truncates data it returns. A result, flag or state token over 64 bytes fails as ErrUnexpectedResponse. Metadata never fails a call: an execution_time, queue_id (over 128 bytes) or retry_token (over 1 KiB) that does not fit is dropped.


Error reference
Every error, and what it matches
What happened Kind errors.Is matches
Invalid key or option, or a nil or zero client (*ValidationError) ErrInvalidConfig
Nil context, or a request failing validation (*ValidationError) ErrInvalidRequest
Context already done before the call (no attempt) canceled / deadline_exceeded context.Canceled / context.DeadlineExceeded
Your context canceled or expired during the call canceled / deadline_exceeded context.Canceled / context.DeadlineExceeded
WithTimeout, WithDownloadTimeout, the http.Client timeout, or a network timeout timeout ErrTimeout and context.DeadlineExceeded
DNS, connection, TLS or proxy failure, reset, truncated or stalled body transport ErrTransport
Envelope auth_failure or bad_referrer; HTTP 401 or 403 unauthorized ErrUnauthorized
Envelope throttle_triggered; HTTP 429 rate_limited ErrRateLimited
Envelope temp_unavail; HTTP 503 unavailable ErrUnavailable
Envelope general_failure; any other HTTP 4xx (413 included) rejected ErrRejected
Any other HTTP 5xx upstream ErrUpstream
HTTP 1xx, 3xx (never followed), a 2xx other than 200, or 600+; an undocumented envelope status; a body that is not a JSON object; an invalid token; another job's status; a results page with more rows than requested, or that contradicts the walk; an undecoded Content-Encoding; a download that is not CSV, or a success envelope instead of a file unexpected_response ErrUnexpectedResponse
Invalid UTF-8 or JSON, trailing data, a repeated key, a missing required field, a wrong type or an out-of-range number malformed_response ErrMalformedResponse
A body or download over its limit, a response over the JSON bounds, or a field over its bound response_too_large ErrResponseTooLarge
DownloadJob's writer failed or wrote short write_failed ErrWriteFailed
WaitForJob saw failed job_failed ErrJobFailed
WaitForJob saw an undocumented state unknown_job_state ErrUnknownJobState
WaitForJob's MaxWait or JobResultPages' MaxPages ran out budget_exhausted ErrBudgetExhausted

The body of a non-200 response is read best-effort, up to 64 KiB, only for APIStatus and the opt-in message: the status alone classifies it. Unwrap returns only a context error or one of the package's fixed causes: never the underlying transport error, a URL, a decoding error or your writer's error.


Privacy and contact data
  • Error strings, GoString, every fmt verb on a Client or an error, and every error in an Unwrap chain never contain the API key, email addresses, row data, remote or callback URLs, callback header values, NeverBounce's messages or URL query data. The key and base URL live only inside function values the Client holds, which fmt and reflection-based dumpers cannot see into.
  • NeverBounce's message is kept only with WithProviderDiagnostics, cut to 1 KiB, with the key replaced by [redacted]; it may still echo the address you checked.
  • CreateJobRequest's String, GoString and Format print only its shape (counts, set or unset) for every fmt verb, because RemoteURL, CallbackURL and CallbackHeaders may carry third-party credentials. fmt cannot call them for %p on a value or for a request held in an unexported struct field, and reflection-based dumpers see every field: keep requests out of such output.
  • The SDK has no logger, telemetry, cache or persistence.
  • Results are contact data. Access control, logging, retention and lawful use are your responsibility, and hashing an address does not anonymize it.

NeverBounce's usage guidelines

The SDK documents these and enforces none:

  • Do not verify an existing list or database one address at a time with CheckEmail: use a job.
  • At most 10 concurrent jobs and 50 runs per day per account.
  • No more than 10 jobs for every 100,000 items per hour; split millions of addresses into chunks of 1 million.
  • Supplied data up to 25 MB; otherwise NeverBounce answers HTTP 413 (the SDK refuses it locally first).

Where NeverBounce's documentation is ambiguous
What NeverBounce's v4.2 documentation leaves open, and what the SDK does
Question SDK behavior
Single-check options are typed as integers in one schema and as booleans elsewhere. JSON true/false everywhere, as the encoding rules allow.
leverage_historical_data is missing from the v4.2 single-check schema. Sent only when you set it (*bool).
Percentages are typed as integers but described as floats. Integers or floats, from 0 to 100.
Errors come in an HTTP 200 envelope, yet schemas show a 400 {}. The envelope decides on 200; any other status decides alone.
input and callback_headers are typed as JSON strings. An array of objects and an object of strings, as the prose and examples show.
The results query echo says page 0 for page 1. Never decoded; Page is what the SDK requested.
data.id goes in as a number and comes back as a string; a header row comes back as a record. Data stays raw JSON; nothing is dropped, deduplicated or correlated by position.
A guide shows an older, flat status shape. Only the nested v4.2 shape is read.
retry_token appears only in a guide example. Kept as opaque text, never sent back.
One page shows a header row in downloads, another does not. Bytes are streamed unchanged; no claim either way.
Units of execution_time; time zone of timestamps; their value before a job starts. Kept as sent: a raw integer, and text never parsed.
The single-check timeout default and range. Not sent unless set; the SDK allows 1 to 300 seconds.
Result order, one row per input, duplicates. NeverBounce's order is kept; nothing is assumed.
The error format of an early download. A JSON envelope is recognized; any other non-CSV answer is refused; nothing is written.
Rate-limit headers, a numeric rate limit, idempotency, a sandbox, callback signing, ordering and delivery. None assumed; nothing is retried or replayed.

What is not covered

account/info, jobs/search, jobs/delete (permanent, so never used for cleanup), poe/confirm, and receiving job callbacks. Older API versions (v4.0, v4.1) are never used. Each missing operation would be added as one more method on Client; see adding an operation.


πŸ“š Documentation

View the generated documentation and NeverBounce's API documentation.

Heads up! go-neverbounce is intentionally light on dependencies. The only external package it uses is the excellent testify suiteβ€”and that's just for our tests. You can drop this library into your projects without dragging along extra baggage.


Development Setup (Getting Started)

Install MAGE-X build tool for development:

# Install MAGE-X for development and building
go install github.com/mrz1836/mage-x/cmd/magex@latest
magex update:install
Library Deployment

This project uses goreleaser for streamlined library releases to GitHub. To get started, install it via:

brew install goreleaser

The release process is defined in the .goreleaser.yml configuration file.

Then create and push a new Git tag using:

magex version:bump bump=patch push=true branch=master
Build Commands

View all build commands

magex help
GitHub Workflows

All workflows are driven by modular configuration in .github/env/ β€” no YAML editing required.

View all workflows and the control center β†’

Updating Dependencies

To update all dependencies (Go modules, linters, and related tools), run:

magex deps:update

πŸ§ͺ Examples & Tests

All unit tests, fuzz tests and examples run via GitHub Actions on Go 1.26.x, the supported baseline. View the configuration file.

Run all tests (fast):

magex test

Run all tests with race detector (slower):

magex test:race

Runnable examples live in the package's Example* functions and in examples/, which plays a synthetic NeverBounce from a local TLS server:

go run ./examples # offline: no key, no network, no cost

Note: tests never touch the network. They use in-memory transports and local TLS servers over HTTP/1.1 and HTTP/2, with synthetic data only.


Live tests

live_probe_internal_test.go (build tag live) runs the SDK against the real NeverBounce API with your own key and logs the shape of each answer, never its values. It is opt-in, so it never runs by default or in CI: it skips unless NEVERBOUNCE_LIVE=1, CI is unset and NEVERBOUNCE_LIVE_KEY is set.

NEVERBOUNCE_LIVE=1 NEVERBOUNCE_LIVE_KEY=secret_... go test -tags live -count=1 -p 1 -run 'TestLiveProbeTier0$' -v .

The free tier (TestLiveProbeTier0) reads an auth_failure and a missing job, and bills nothing. The paid tier (TestLiveProbeTier1) also needs NEVERBOUNCE_LIVE_ACK_BILLING=yes-i-accept-charges and an address you own in NEVERBOUNCE_LIVE_EMAIL: it spends one credit and creates a sample job that stays in your account.


⚑ Benchmarks

Run the Go benchmarks:

magex bench

πŸ“Š Performance Results
Benchmark Iterations ns/op B/op allocs/op
DecodeCheckEmail 3,251,857 3,696 1,440 30
CheckEmailEndToEnd 1,989,206 6,032 5,258 68
DecodeResultsPage1000 3,625 3,313,265 572,156 16,016
EncodeCreateJob10k 14,036 853,493 466,992 3
CheckStrict8MiB 535 22,439,044 824 7
DownloadCopy 5,053 2,380,973 110,968 42

DecodeCheckEmail decodes a full single-check answer; CheckEmailEndToEnd makes a whole CheckEmail call against an in-memory transport; DecodeResultsPage1000 decodes a 1000-row results page; EncodeCreateJob10k validates and encodes a 10,000-row list; CheckStrict8MiB runs the strict JSON checks over an 8 MiB body; DownloadCopy streams 64 MiB to io.Discard (about 28 GB/s). They measure local CPU work only, executed with magex bench on an Apple M1 Max (ARM64) with Go 1.27.2, and make no claim about network or NeverBounce latency, which dominates real calls.


πŸ› οΈ Code Standards

Read more about this Go project's code standards.


πŸ€– AI Usage & Assistant Guidelines

Read the AI Usage & Assistant Guidelines for details on how AI is used in this project and how to interact with the AI assistants.


πŸ‘₯ Maintainers

MrZ
MrZ

🀝 Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome πŸ™Œ! The most basic way to show your support is to star 🌟 the project, or to raise issues πŸ’¬. You can also support this project by becoming a sponsor on GitHub πŸ‘ or by making a bitcoin donation to ensure this journey continues indefinitely! πŸš€

Stars


πŸ“ License

License

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 ΒΆ

Examples ΒΆ

Constants ΒΆ

View Source
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 ΒΆ

View Source
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")

	// ErrUnauthorized reports a refused API key: the envelope status
	// 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")

	// ErrUnavailable reports the envelope status temp_unavail or HTTP 503: a
	// 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 means a partial service interruption.
	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.

func (APIStatus) Known ΒΆ

func (s APIStatus) Known() bool

Known reports whether s is one of the six documented 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 ΒΆ

func (e *CallError) Error() string

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 ΒΆ

func (e *CallError) GoString() string

GoString prints the exported metadata only, so that %#v cannot reach the cause or the provider diagnostics.

func (*CallError) Is ΒΆ

func (e *CallError) Is(target error) bool

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 ΒΆ

func (e *CallError) Unwrap() error

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 ΒΆ

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

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 ΒΆ

func (c *Client) GoString() string

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 ΒΆ

func (c *Client) JobStatus(ctx context.Context, req JobStatusRequest) (*JobStatus, error)

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 ΒΆ

func (c *Client) String() 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 ΒΆ

func (c *Client) WaitForJob(ctx context.Context, req WaitForJobRequest) (*JobStatus, error)

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 matches ErrUnauthorized.
	FailureUnauthorized FailureKind = "unauthorized"

	// FailureRateLimited matches ErrRateLimited.
	FailureRateLimited FailureKind = "rate_limited"

	// FailureUnavailable matches ErrUnavailable.
	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.

func (Flag) Known ΒΆ

func (f Flag) Known() bool

Known reports whether f is one of the 22 documented v4.2 flags.

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.

func (Flags) Has ΒΆ

func (fs Flags) Has(f Flag) bool

Has reports whether fs contains f, compared exactly.

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.

func (JobID) String ΒΆ

func (id JobID) String() string

String returns the decimal form, such as "289022".

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 ΒΆ

func (s JobState) InProgress() bool

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) Known ΒΆ

func (s JobState) Known() bool

Known reports whether s is one of the nine documented states.

func (JobState) NeedsAction ΒΆ

func (s JobState) NeedsAction() bool

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).

func (JobState) Terminal ΒΆ

func (s JobState) Terminal() bool

Terminal reports whether the job has ended: complete or failed.

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.

const (
	LineFeedLFCR LineFeed = "LINEFEED_0A0D" // "\n\r", the provider's default
	LineFeedCRLF LineFeed = "LINEFEED_0D0A" // "\r\n"
	LineFeedLF   LineFeed = "LINEFEED_0A"   // "\n"
	LineFeedCR   LineFeed = "LINEFEED_0D"   // "\r"
)

Line endings.

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 ΒΆ

func WithDownloadTimeout(d time.Duration) Option

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 ΒΆ

func WithHTTPClient(hc *http.Client) Option

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 ΒΆ

func WithMaxDownloadBytes(n int64) Option

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 ΒΆ

func WithMaxResponseBytes(n int64) Option

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 ΒΆ

func WithTestBaseURL(rawURL string) Option

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 ΒΆ

func WithTimeout(d time.Duration) Option

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.

func (Result) Known ΒΆ

func (r Result) Known() bool

Known reports whether r is one of the five 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.

func (ResultRow) Column ΒΆ

func (r ResultRow) Column(name string) (value string, ok bool)

Column returns the value of the member name in r.Data, matched exactly: a JSON string decoded, or a JSON number as its literal text. ok is false when Data is not an object, has no such member, or holds another type there.

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 ΒΆ

type ValidationError struct {
	Err    error
	Field  string
	Reason string
}

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.

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.

Jump to

Keyboard shortcuts

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