enformion

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 24 Imported by: 0

README

🔎  go-enformion

A small, standard-library-only Go SDK for the EnformionGO developer APIs.


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-enformion is a Go SDK for the EnformionGO developer APIs (Enformion, LLC). Every API it supports shares one deliberately narrow and strict core: one HTTP attempt per call, no retries or redirects, bounded reads, strict JSON decoding, and errors that never contain credentials, personal data or provider text.

Two APIs are supported today:

  • Contact Enrichment (POST https://devapi.enformion.com/Contact/Enrich, search type DevAPIContactEnrich). Give it a subject with at least two of name, phone, email and address, and it returns the provider's top person match (name, age, addresses, phones and emails).
  • Person Search (POST https://devapi.enformion.com/PersonSearch, in one of four documented search modes). Give it a mode and at least one criterion, and it returns one page of the provider's candidate persons, with their names, addresses, phones, emails, relatives, associates and indicators.

Both return typed Go values, with every field optional and nothing invented. The rest of the EnformionGO API is planned for future releases: see Supported APIs.


🧭 Supported APIs

go-enformion adds the EnformionGO APIs one at a time. Each arrives as its own method on Client, with its own request and result types, without breaking existing callers. The list follows the provider's API reference; PRO marks the endpoints it labels as Pro.

Category API Status
Single result Contact Enrichment Available: EnrichContact
Contact Enrich Plus Planned
Caller ID Planned
Caller ID Plus Planned
Email ID Planned
Email ID Enrich Plus Planned
Contact ID Planned
Contact ID Plus Planned
Address ID Planned
Address ID Plus Planned
Address AutoComplete Planned
Lead verification ELeadVerify Planned
People data Person Search Available: SearchPersons
ID Verification Planned
Census Search Planned
Debt Search V2 PRO Planned
Divorce Search Planned
Marriage Search PRO Planned
Reverse Phone Search Planned
LinkedIn ID Planned
Business data Business Search Planned
Business ID Planned
Domain Search Planned
Workplace Search Planned
Workplace drilldown lookups (states, cities, industries, levels, departments, job titles) Planned
Property data Property Search V2 Planned
Court records Criminal Search V2 PRO Planned
Eviction Search PRO Planned
Pre-Foreclosure Search PRO Planned
Asset data OFAC Search PRO Planned
Vehicle Ownership PRO Planned
License data DEA Search PRO Planned
Professional License Search PRO Planned
Data alerts Data Alerts (subscriptions, alerts and push notifications) Planned

Each new API is a new billable surface with its own data, terms and contract, so each is added only after its own review; see docs/adding-an-operation.md.


📦 Installation

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

go get github.com/mrz1836/go-enformion

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


Credentials

EnformionGO authenticates with an API key name and password, copied from the Keys tab of the dashboard at api.enformion.com. The SDK sends them as the galaxy-ap-name and galaxy-ap-password headers. It never reads credentials from environment variables or files: your application decides where the secrets come from and passes them to NewClient. Keeping them secret in your own configuration and logs is your application's job.


🏁 Quick Start

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"time"

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

func main() {
	// Your application chooses where the secrets come from.
	client, err := enformion.NewClient(loadKeyName(), loadKeyPassword(),
		enformion.WithTimeout(10*time.Second),
	)
	if err != nil {
		log.Fatal(err) // never quotes the secrets
	}

	// Two categories: name and email. This call is live and billable.
	res, err := client.EnrichContact(context.Background(), enformion.EnrichContactRequest{
		FirstName: "Avery",
		LastName:  "Example",
		Email:     "avery.example@example.com",
	})
	if errors.Is(err, enformion.ErrRateLimited) {
		log.Fatal("rate limited or monthly quota reached; the SDK never retries")
	}
	if err != nil {
		log.Fatal(err) // safe to log: kind, HTTP status and field path only
	}
	if res.Person == nil {
		fmt.Println("no person data returned (not proof that no match exists)")
		return
	}
	p := res.Person
	fmt.Println(p.Name.FirstName, p.Name.LastName, p.Age)
	for _, ph := range p.Phones {
		fmt.Println(ph.Number, ph.Type)
	}
}

💡 Usage

Configure a client

NewClient(keyName, keyPassword string, opts ...Option) validates everything up front and performs no I/O. A Client is immutable and safe for concurrent use; create one and reuse it.

Option Default Limits Effect
WithTimeout(d) 30s 0 < d ≤ 5m Bounds each call, including reading the whole body. The context deadline applies too.
WithMaxResponseBytes(n) 1 MiB for EnrichContact, 16 MiB for SearchPersons 1 B to 16 MiB Limits the (decompressed) response body. Once given, n applies to every operation.
WithHTTPClient(hc) fresh transport non-nil Calls go through a copy of hc that refuses redirects and has no cookie jar; hc is never modified.
WithTestBaseURL(url) production https on 127.0.0.0/8 or [::1] Points the client at a local test server. There is no other base URL option.
WithProviderDiagnostics() off Keeps provider messages on errors, reachable only through (*CallError).Diagnostics().

Credentials must each be 1 to 1024 bytes of printable ASCII with no leading or trailing spaces. Invalid arguments return a *ValidationError matching ErrInvalidConfig that names the argument, never its value.


Contact Enrichment

EnrichContact sends one subject and returns the provider's top person match.


Build a request
req := enformion.EnrichContactRequest{
	FirstName:    "Avery",
	MiddleName:   "Q",
	LastName:     "Example",
	DOB:          "06/01/1985",        // mm/dd/yyyy, zero-padded, a real date
	Age:          41,                  // 0 = not sent
	AddressLine1: "100 Sample Way",    // house number and street, or PO Box
	AddressLine2: "Exampleton, OH",    // city and state, state, or ZIP
	Phone:        "(312) 555-0142",
	Email:        "avery.example@example.com",
	SessionID:    "batch-7f3a9c-0001", // optional opaque logging ID, never personal data
}

The provider requires at least two of four categories. The SDK counts them as follows, and refuses a request with fewer before sending anything:

Category Counts when
Name FirstName and LastName are set. MiddleName alone, or a lone first or last name, is sent but does not count.
Phone Phone is set.
Email Email is set.
Address AddressLine1 or AddressLine2 is set.

DOB and Age are sent when set but are not categories. Values are sent verbatim, never trimmed or rewritten. Every text field must be valid UTF-8 of at most 256 bytes, with no control characters and not only whitespace; these are SDK limits, as the provider documents none. The phone format is not enforced, because the provider's own examples disagree with its documented formats. SessionID must be empty or 1 to 128 bytes of visible ASCII.


Read the result
res, err := client.EnrichContact(ctx, req)
if err != nil {
	return err
}
if res.Person == nil {
	return nil // no person data in the response; NOT proof that no match exists
}
for _, ph := range res.Person.Phones {
	connected := "not reported"
	if ph.IsConnected != nil {
		connected = strconv.FormatBool(*ph.IsConnected) // a provider flag, not consent to contact
	}
	fmt.Println(ph.Number, ph.Type, connected, ph.LastReportedDate)
}
if res.IdentityScore != nil {
	fmt.Println("provider identityScore (uninterpreted):", *res.IdentityScore)
}
Field Type Absent or null Notes
Person *Person nil nil also when the person object holds no data at all.
IdentityScore *int nil An uninterpreted provider integer: not a probability or confidence. 0 is &0.
RequestID string "" Kept only when 1 to 128 visible ASCII bytes.
Diagnostics ProviderDiagnostics empty The envelope's message, error.inputErrors and error.warnings, bounded. May echo personal data.
Person.PersonID, Age, PartialDOB string "" Provider text. Age is a string on the wire.
Person.Name Name zero FirstName, MiddleName, LastName.
Addresses, Phones, Emails slices nil Provider order, every entry kept; JSON null elements are not entries. More than 1,000 entries fails the call (an SDK safety bound; the provider documents at most five).
Phone.IsConnected, Email.IsValidated, Email.IsBusiness *bool nil nil means not reported; false is &false. None is consent to contact.

Dates are provider text (shown as M/D/YYYY without padding in the documentation's examples) and are never parsed. The SDK never deduplicates, truncates, ranks, picks a "preferred" entry or infers relationships. The result is the provider's top match, not identity verification.

Results marshal to JSON and back unchanged (reflect.DeepEqual); that JSON is this SDK's own serialization, not the provider's wire format.


SearchPersons sends one page request in one of the four documented search modes and returns that page of the provider's candidate persons. The provider's terms apply to every search: see Personal data and permitted use.


Build a request
req := enformion.PersonSearchRequest{
	Mode:      enformion.PersonSearchModePerson, // required: the search type header
	FirstName: "Avery",
	LastName:  "Example",
	Addresses: []enformion.PersonSearchRequestAddress{
		{AddressLine2: "Exampleton, OH"}, // city and state, state, or ZIP
	},
	Includes:       []enformion.PersonSearchInclude{enformion.PersonSearchIncludeAddresses},
	FilterOptions:  []enformion.PersonSearchFilter{enformion.PersonSearchFilterIncludeLowQualityAddresses},
	Page:           1,  // 0 = provider default
	ResultsPerPage: 10, // 0 = provider default
	SessionID:      "batch-7f3a9c-0001",
}

The mode is sent as the galaxy-search-type header, never in the body. The provider documents four:

Mode Search type Documented as
PersonSearchModePerson Person Detailed results, mainly for "logged in or paying" users
PersonSearchModeTeaser Teaser For "logged out" users: "Most of the data elements in a teaser search are masked and/or limited by the quantity returned"; suggested as the initial search
PersonSearchModeReversePhonePerson ReversePhonePerson The same text as Person. A mode of Person Search, not the separate Reverse Phone Search API
PersonSearchModeReversePhonePersonTeaser ReversePhonePersonTeaser The same text as Teaser

At least one criterion is required: a name part, an AKA, DOB, an age field, an address, Email, Phone, ClientIP, a relative or a Tahoe ID. The SDK adds no rule the provider does not document: it does not decide which criteria a mode needs (a reverse-phone mode does not require Phone) or which age field wins. Every limit below is the SDK's own, as the provider documents none.

Field Sent as Rules
FirstName, MiddleName, LastName the same names Text rules: valid UTF-8, at most 256 bytes, no control characters, not only whitespace
AKAs, Relatives Akas, Relatives: lists of {FirstName, MiddleName, LastName} At most 32 entries; an entry with every field empty is blank. The shape is unverified
DOB Dob mm/dd/yyyy, zero-padded, a real date
Age, AgeRangeMinAge, AgeRangeMaxAge the same names 0 (not sent) or 1 to 150; never checked against each other
AgeRange AgeRange N-M: one to three digits each, each at most 150
Addresses Addresses: a list of {AddressLine1, AddressLine2, County} At most 32 entries; an entry with every field empty is blank
Email, Phone the same names Text rules; the phone format is not enforced
ClientIP ClientIp A canonical dotted IPv4 address, sent as a string (unverified: the provider types it as an integer)
TahoeIDs TahoeIds At most 32 IDs, none empty, such as a result's TahoeID
FirstNameCharOffset, LastNameCharOffset the same names nil (not sent) or 0 to 256; new(0) sends 0
DOBFormat DobFormat Text rules, sent verbatim
MaxAddressYears, MaxPhoneYears the same names nil (not sent) or 0 to 150; new(0) sends 0
Includes, FilterOptions the same names At most 32 tokens each, 1 to 128 ASCII letters and digits, sent verbatim, in order, duplicates kept
Page, ResultsPerPage the same names 0 (provider default) or from 1; ResultsPerPage at most 1,000
SessionID galaxy-client-session-id header Empty, or 1 to 128 bytes of visible ASCII

Includes and filters are enabled per account by the provider. Its includes page lists labels rather than tokens, and only Addresses and PhoneNumbers appear as tokens in its documentation; the PersonSearchInclude constants also cover EmailAddresses, DatesOfBirth, Relatives, RelativesSummary and Associates, which have been observed to be accepted. The PersonSearchFilter constants quote the provider's descriptions, several of which contradict the filter's name; the SDK sends the token and does not interpret it. Any other alphanumeric token can be passed as PersonSearchInclude("...") or PersonSearchFilter("...").

A failure names the field and list index, never the value, such as enformion: invalid request: Addresses[1].County: control_character. The new reasons are unsupported (an unknown mode), too_many (a list over 32 entries) and no_criteria.


Read the result
page, err := client.SearchPersons(ctx, req)
if err != nil {
	return err
}
for _, p := range page.Persons { // the provider's order; duplicates kept
	fmt.Println(p.TahoeID, p.FullName)
	for _, ph := range p.PhoneNumbers {
		connected := "not reported"
		if ph.IsConnected != nil {
			connected = strconv.FormatBool(*ph.IsConnected) // a provider flag, not consent to contact
		}
		fmt.Println(" ", ph.PhoneNumber, ph.PhoneType, connected)
	}
}
if len(page.Persons) == 0 {
	// no candidates in the response; NOT proof that no match exists
}
Field Type Absent or null Notes
Persons []PersonSearchPerson nil The page's candidates, in the provider's order, duplicates kept. null or [] is a page without candidates; an envelope without persons fails as ErrUnexpectedResponse.
Pagination PersonSearchPagination zero CurrentPageNumber, ResultsPerPage, TotalPages, TotalResults, each *int. The member names are inferred.
Counts PersonSearchCounts zero The provider's counts: uninterpreted *int counts and SearchResultsOverflow *bool.
RequestID string "" Kept only when 1 to 128 visible ASCII bytes.
CriteriaType, SmartSearchStatistics json.RawMessage nil Undocumented structure, kept raw. May echo the request's personal data.
Diagnostics ProviderDiagnostics empty As for Contact Enrichment.
PersonSearchPerson.TahoeID, FullName, DOB, DOD, dates string "" Provider text, never parsed; teaser modes may mask it. IsCurrentPropertyOwner is text too.
Age, SparseFlag *int nil 0 is &0.
IsPublic, IsPremium, IsOptedOut, IsEnterpriseOptedOut, HasAdditionalData *bool nil Provider flags, not consent or eligibility.
Name, AKAs, MergedNames PersonSearchName zero, nil Prefix, name parts, suffix, RawNames, first-seen dates and a raw SourceSummary.
Addresses, PhoneNumbers, EmailAddresses, Locations, DatesOfBirth slices nil Every entry kept; more than 1,000 entries fails the call. Coordinates, ZIP codes and hashes are text.
RelativesSummary, AssociatesSummary slices nil The provider's summaries of other people. Its labels (RelativeType) and Score are its own; the SDK infers no relationship.
Associates []PersonSearchPerson nil Full associated persons (the Associates include), decoded one level deep.
Indicators PersonSearchIndicators zero Nineteen *int record indicators, uninterpreted: counts above 1 have been observed.
Extra map[string]json.RawMessage nil Every person member the SDK does not decode, by its key as sent: see raw and ignored members.

The SDK never selects, ranks, merges or deduplicates candidates or entries, and never picks a "best" match. A candidate is the provider's observation, not identity verification. Results marshal to JSON and back unchanged (reflect.DeepEqual), in this SDK's own serialization.


Pages

Each call returns one page. The SDK never fetches the next one: ask for it explicitly, knowing that each page is a separate call that may be billed.

req.Page = 2
next, err := client.SearchPersons(ctx, req) // a second, separately billable call

Handle errors

Validation failures are *ValidationError values, and nothing was sent. Every other failure is a *CallError whose Kind matches one target with errors.Is (a timeout matches two):

Kind Matches When
unauthorized ErrUnauthorized HTTP 401 or 403
rate_limited ErrRateLimited HTTP 429 (rate limit or monthly quota). The SDK never retries.
rejected ErrRejected Another 4xx (a 404 is never a "no match"), or HTTP 200 with isError: true
upstream ErrUpstream HTTP 5xx
unexpected_response ErrUnexpectedResponse 1xx, 3xx (never followed), another 2xx, 600 and above, a body that is not an object, a missing or non-boolean isError, a Person Search body without persons, or a person or one of its record entries (a name, address, phone, email and, for Person Search, a location, relative, associate, date of birth or death record) whose only data is under unrecognized keys
malformed_response ErrMalformedResponse Invalid UTF-8 or JSON, trailing data, a repeated key, or a recognized field of the wrong type
response_too_large ErrResponseTooLarge An HTTP 200 body over the limit, a decoded list of more than 1,000 entries, or a Person Search body that would decode to more than four times its size plus 1 MiB
transport ErrTransport DNS, connection, TLS, proxy, reset or truncated body
timeout ErrTimeout and context.DeadlineExceeded The SDK's timeout, an http.Client timeout, or a network timeout
canceled context.Canceled The caller's context was canceled
deadline_exceeded context.DeadlineExceeded The caller's context deadline expired
var (
	ve *enformion.ValidationError
	ce *enformion.CallError
)
switch {
case errors.As(err, &ve):
	// not sent: fix the request (ve.Field, ve.Reason)
case errors.Is(err, enformion.ErrTimeout): // check before context.DeadlineExceeded
case errors.Is(err, context.DeadlineExceeded):
case errors.Is(err, enformion.ErrRateLimited):
case errors.Is(err, enformion.ErrRejected):
	if errors.As(err, &ce) {
		_ = ce.Diagnostics() // only with WithProviderDiagnostics; may echo personal data
	}
}

Error() holds only the kind, the HTTP status and a JSON field path, such as enformion: malformed_response (HTTP 200): person.phones[1].isConnected, so errors are safe to log. CallError exposes Kind, StatusCode, RequestID and Field; tests may build one from those fields and it matches errors.Is like a real one.


In a net/http handler
func (s *Server) HandleEnrich(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
	defer cancel()
	res, err := s.Enricher.EnrichContact(ctx, requestFrom(r))
	if err != nil {
		s.Log.WarnContext(ctx, "contact enrichment failed", "error", err) // PII-free
		http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
		return
	}
	if res.Person == nil {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	_ = json.NewEncoder(w).Encode(res.Person)
}

Testing your application

Depend on a small interface you own, and fake it in tests:

type ContactEnricher interface {
	EnrichContact(context.Context, enformion.EnrichContactRequest) (*enformion.EnrichContactResult, error)
}

var _ ContactEnricher = (*enformion.Client)(nil)

type PersonSearcher interface {
	SearchPersons(context.Context, enformion.PersonSearchRequest) (*enformion.PersonSearchResult, error)
}

var _ PersonSearcher = (*enformion.Client)(nil)

fake := &fakeEnricher{err: &enformion.CallError{Kind: enformion.FailureRateLimited, StatusCode: 429}}
// errors.Is(err, enformion.ErrRateLimited) is true for the fake's error too.

To exercise the real client offline, serve synthetic responses from httptest.NewTLSServer and point the client at it with WithTestBaseURL(srv.URL) and WithHTTPClient(srv.Client()). The package's runnable examples do exactly that.


⚙️ Behavior

Billing, retries and timeouts
  • devapi.enformion.com is the only server the provider documents. Every call is live, and the provider's pricing and help pages say it bills per successful match. There is no documented sandbox.
  • Each call makes at most one HTTP attempt. The SDK never retries, follows a redirect, polls, hedges or makes a follow-on call, and it disables the standard library's own resends (GetBody is nil, so neither HTTP/1 nor HTTP/2 can replay the POST, and no idempotency header is sent).
  • Invalid requests, and calls whose context is already done, send nothing.
  • After a timeout, cancellation, transport failure, oversized body or unreadable response, the provider may already have processed and billed the request. The SDK cannot tell, and makes no claim about what was or was not billed. Repeating a call may be billed again.
  • An injected http.Client's transport is trusted: it sees the credential headers and the request's personal data, and it may retry on its own.
  • An httptrace.ClientTrace on the context still runs, but its WroteHeaderField hook never receives the galaxy-ap-name or galaxy-ap-password headers, so tracing libraries that record request headers cannot capture the credentials. The standard library's own debug logging is outside the SDK's control: GODEBUG=http2debug=2 logs every request header, credentials included, so never enable it with real credentials.
  • The default transport honors HTTPS_PROXY and NO_PROXY, as Go's default transport does. To bypass proxies, inject a client whose transport sets no Proxy.
Personal data and permitted use

Requests and results hold personal data. The library never logs, prints, stores or caches anything and never reads credentials or configuration from the environment, but its request and result types have no redacting formatter: access control, logging, retention, security and permitted use are your application's responsibility. Serializing or hashing personal data does not anonymize it. Error strings never contain personal data; provider diagnostics on errors are off unless you opt in. Person Search results also describe other people (relatives, associates and neighbors) and keep undocumented members as raw JSON, which prints in full.

A result is the provider's observation, not identity verification: no match, candidate, label, score, indicator or flag establishes anyone's identity, consent or eligibility for any purpose.

The provider's terms restrict use of its data. In summary, and with no claim of legal suitability (read the current terms yourself):

  • It is not a consumer reporting agency under the FCRA. Its data may not be used as a factor in eligibility for credit, insurance, employment, housing or any other FCRA purpose.
  • Results may not be stored or cached to make additional inquiries, merged with other data, scraped or resold.
  • Minors, celebrities and public figures may not be searched.
  • Compliance with CAN-SPAM, the TCPA and Do Not Call rules is yours: the provider scrubs no numbers. IsConnected, IsValidated and IsBusiness are provider flags, not consent to contact anyone.
Contact Enrichment: when no person comes back

The provider does not document what a "no match" looks like. When an HTTP 200 response with isError: false has no person, a null one, or one with no data at all, the result's Person is nil. That means only that the response carried no person data: it is not a verified no-match, and the SDK returns no ErrNoMatch. A person object, its name, or any address, phone or email entry whose only data sits under keys the SDK does not recognize (as after a field rename) fails the call as ErrUnexpectedResponse instead, so a billed match never silently comes back empty. An HTTP 404 is a rejection, never a "no match".

Contact Enrichment: response members the SDK ignores

These members of the response are never decoded or type-checked, so a change in their contents cannot fail a call. The whole-body checks (valid UTF-8 and JSON, no repeated keys) still cover them, and a person whose only data is under relatives fails as ErrUnexpectedResponse, like any person without recognized data. Any of them could be added later without breaking callers.

Member Why it is excluded
person.relatives Third-party personal data, outside subject contact enrichment
searchCriteria Echoes the request's personal data
pagination No paging contract; the documented sample reports totalResults: 0 beside a match
databaseQueryInfo Undocumented internals
requestType, totalRequestExecutionTimeMs Diagnostics with no documented use
Contact Enrichment: limits and unverified assumptions

Built from the provider's Contact Enrichment documentation (readme.io docs version 1.4), which leaves these open. None has been checked against the live API:

Open question What the SDK does until it is resolved
What a no-match response looks like Person == nil for no person data; never declared a no-match
Whether a validation failure is HTTP 400 {} or HTTP 200 with isError: true, and what inputErrors and warnings entries look like Both are rejected; entries are kept as raw JSON
Authentication failure status and body 401 and 403 are unauthorized; anything else is classified by status
Rate and quota signals, Retry-After 429 is rate_limited; no retry hint is exposed
Address key casing (addressLine1 in every valid example, AddressLine1 in the properties table) Sends addressLine1 and addressLine2
Which envelope and person fields the standard tier returns (requestId, personId, partialDob) Every field is optional
What counts as a billable match No billing claim is made
Header strictness Always sends galaxy-ap-name, galaxy-ap-password and galaxy-search-type
Length limits SDK limits only: 256 bytes per text field, 128 for SessionID, 1,000 entries per person list

The documentation's own 200 example is not valid JSON. The test fixtures were written from scratch to its shape with synthetic values. An opt-in live probe, run only by the maintainer, exists to settle the no-match, validation-failure, authentication-failure and address-casing questions (none probes rate limits); see Examples & Tests.

Person Search: pages, modes and billing
  • Each SearchPersons call is one live, potentially billable call for one page. The provider documents no Person Search pricing, so the SDK makes no billing claim beyond that.
  • The SDK never fetches a next page, never upgrades a Teaser search to Person, never retries a page and never makes a follow-up call, such as a search by a returned TahoeID. Each of those is a separate call your application chooses to make.
  • A page without candidates means only that the response carried none: it is not a verified no-match. A refusal (a 4xx, or isError: true) is an error, never an empty page, and never returns candidates.
  • Person Search's response limit defaults to 16 MiB, the maximum, because a page can hold many people: one person with every include, associates among them, can be a few hundred kilobytes. A larger body fails with ErrResponseTooLarge after the call may have been billed, so size ResultsPerPage and Includes to fit. WithMaxResponseBytes, once given, sets the limit for every operation.
  • The SDK decodes candidates in the provider's order and keeps duplicates. It never selects, ranks, merges or deduplicates them.
Person Search: raw and ignored members

Members whose structure the provider does not document are kept as raw JSON rather than guessed at:

Member Kept as
sourceSummary (names, addresses, phones, emails, dates of birth, death records) SourceSummary json.RawMessage
datesOfDeath entries DatesOfDeath []json.RawMessage
an address's neighbors and neighborSummaryRecords entries []json.RawMessage
criteriaType, smartSearchStatistics json.RawMessage on the result
every other person member, such as driversLicenseDetail or relatives, and an associate's own associates PersonSearchPerson.Extra, keyed as sent

Raw values are copies, never aliasing the response, normalized as encoding/json marshals a json.RawMessage (compact, with <, >, &, U+2028 and U+2029 escaped, and unpaired surrogate escapes replaced), so results round-trip unchanged. JSON null is nil, and null person members are left out of Extra.

They are opaque personal data, often about other people: the SDK never types or interprets them, and printing one prints all of it. They also cost memory. The response limit bounds the body, and a decode budget of four times the body's size plus 1 MiB bounds what the body may decode to, so that a hostile response of nested empty lists fails with ErrResponseTooLarge instead of costing a hundred times its size. Real pages decode to less than their own size.

A record whose only data is under keys the SDK does not decode (a person, a name, an address, a phone, an email, a location, a relative, an associate, a date of birth or a death record) fails as ErrUnexpectedResponse, so a renamed field never makes a billed page come back silently empty. A person keeps its unknown members in Extra, but still fails when none of its members is recognized. The flag and metadata objects (pagination, counts, indicators, highRiskMarker, emailEngagementData) ignore members they do not know, so a new indicator never fails a page.

These envelope members are never decoded or type-checked: searchCriteria (it echoes the request's personal data), databaseQueryInfo, requestType, requestTime and totalRequestExecutionTimeMs. The whole-body checks (valid UTF-8 and JSON, no repeated keys) still cover them.

Person Search: limits and unverified assumptions

Built from the provider's Person Search documentation (readme.io docs version 1.4) and an observed response structure (key names and types only). The documentation leaves these open, and none has been checked against the live API by this SDK's tests:

Open question What the SDK does until it is resolved
The response envelope: the documentation's only example is one PascalCase person, without persons, pagination, isError or requestId Follows the observed camelCase envelope; keys match without regard to ASCII case, so the documented PascalCase decodes too
The pagination member names, observed only as {} Decodes currentPageNumber, resultsPerPage, totalPages and totalResults, as the provider's other endpoints name them
The shape of Akas and Relatives (documented as an undefined Name{}) Sends lists of {FirstName, MiddleName, LastName}
ClientIp, typed as an integer with a dotted format Sends a canonical dotted IPv4 string
TahoeIds (documented) or a single TahoeId Sends the TahoeIds list
Include tokens: the includes page lists labels such as "Workplace Summary" Constants for the two documented and five observed tokens; any other token is sent as given
Filters whose descriptions contradict their names Sent verbatim; the SDK never interprets them
What Teaser and the reverse-phone modes mask or limit, and how Every value is kept verbatim; nothing is inferred from a mask
The types of a relative's score and flags Integers and booleans; another type fails as ErrMalformedResponse
Whether a validation failure is HTTP 400 {} or HTTP 200 with isError: true Both are rejected
What, and how much, is billed No billing claim is made
Length limits SDK limits only: 32 entries per request list, 128-byte tokens, 1,000 entries per page and per response list, and the decode budget

The test fixtures were written from scratch to these shapes with synthetic values. The opt-in live probe's search-nomatch and search-validation probes exist to settle the envelope, pagination and validation-failure questions; see Examples & Tests.

Scope and extension

Contact Enrichment and Person Search are implemented today; every other API in Supported APIs is planned, and none is stubbed. The SDK has no automatic paging and no batch requests. Each arrives as a new method on Client with its own request and result types, added without breaking existing callers; see docs/adding-an-operation.md.


📚 Documentation

View the generated documentation and the provider's API reference.

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 binary and library deployment 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

Unit tests and examples run via GitHub Actions on Go 1.26.x (the supported baseline) and the current Go release; fuzz tests run on the baseline. View the configuration file.

Run all tests (fast):

magex test

Run all tests with race detector (slower):

magex test:race

Run the fuzz tests briefly:

magex test:fuzz time=5s

Unit tests never leave the machine: they use in-memory transports and loopback TLS servers with synthetic data. They prove, among other things, the exact wire request, the full status table, zero calls for invalid input, exactly one attempt on every failure (including HTTP/2 stream resets), that redirects never reach their target, bounded reads, timeouts during the body read, safe concurrent use across operations, that hostile Person Search bodies fail on the decode budget instead of costing many times their size, and that credentials and personal data never appear in errors or formatted output.

The runnable Example* functions in example_test.go run offline against a local TLS server.


Live contract probe

An opt-in probe in live_probe_internal_test.go makes real, potentially billable calls to settle the open questions above. It is run only by the maintainer, by hand. It needs the live build tag and these variables:

Variable Effect
ENFORMION_LIVE=1 Enables the probe; without it the probe skips.
ENFORMION_LIVE_ACK_BILLING=I-understand Acknowledges that calls may be billed; without it the probe skips.
CI Must be unset; when set, the probe skips.
ENFORMION_LIVE_PROBES Comma-separated probes. Contact Enrichment: nomatch, validation and auth take 1 call each, casing takes 2. Person Search: search-nomatch (a Teaser search for an invented subject, one result at most) and search-validation (an empty {} body) take 1 call each.
ENFORMION_AP_NAME, ENFORMION_AP_PASSWORD Credentials, read only by the test harness.

Once enabled, the probe fails before sending anything when ENFORMION_LIVE_PROBES names no known probe, when the chosen probes need more than 4 calls (all six together need 7), or when the credentials are invalid.

go test -tags live -count=1 -p 1 -run TestLiveProbe -v .

The magex test targets and CI compile the probe with the live tag too, and it skips there unless ENFORMION_LIVE and ENFORMION_LIVE_ACK_BILLING are set, so set them only for the run.

A run makes at most 4 calls, never retries, and stops at the first HTTP 429. It prints only the response shape (status, response header names, the JSON type tree with identifier-like key names, and the isError flag), never a value, and discards unprinted any response that unexpectedly holds person data. The Person Search probes have not been run yet: running search-nomatch and search-validation is the check to make before relying on that operation's unverified assumptions.


⚡ Benchmarks

Run the Go benchmarks:

magex bench

Benchmarks measure local CPU work and allocations only (validation, encoding, strict checks and decoding) with in-memory transports. They say nothing about network or provider 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 enformion is a small, standard-library-only Go client for two operations of the EnformionGO developer APIs (Enformion, LLC):

Create a Client with NewClient and the dashboard's API key name and password. Call EnrichContact with at least two of the four documented search categories (name, phone, email and address), or SearchPersons with a mode and at least one criterion. Results hold the provider's data with typed, optional fields.

client, err := enformion.NewClient(keyName, keyPassword)
if err != nil {
	return err
}
res, err := client.EnrichContact(ctx, enformion.EnrichContactRequest{
	FirstName: "Avery", LastName: "Example", Email: "avery.example@example.com",
})
page, err := client.SearchPersons(ctx, enformion.PersonSearchRequest{
	Mode: enformion.PersonSearchModePerson, FirstName: "Avery", LastName: "Example",
})

Calls and billing

devapi.enformion.com is the only server the provider documents. Every call to it is live, and the provider's pricing pages say it bills per successful match; there is no documented sandbox. Each call makes at most one HTTP attempt: the SDK never retries, follows a redirect, polls, hedges or makes a follow-on call, and it disables the standard library's own automatic resends. A SearchPersons call returns one page: each page, and each change of mode, is a separate call that may be billed, and the SDK never fetches a next page or upgrades a teaser search on its own. An injected http.Client's transport is trusted and may still retry on its own. After a timeout, a cancellation, a transport failure or an unreadable response, the provider may already have processed and billed the request. The SDK makes no claim about what was or was not billed.

Requests that fail local validation, and calls whose context is already done, send nothing.

An httptrace.ClientTrace on the context still runs, but its WroteHeaderField hook never receives the credential headers. The standard library's own debug logging (GODEBUG=http2debug=2) prints every request header, credentials included, and must not be enabled with real credentials.

Errors

Validation failures are *ValidationError values matching ErrInvalidConfig or ErrInvalidRequest. Every other failure is a *CallError, whose Kind matches one sentinel (or context.Canceled or context.DeadlineExceeded) with errors.Is. Error strings hold only the kind, the HTTP status and a JSON field path: never credentials, request values, URLs, response bodies or provider messages. Provider messages, inputErrors and warnings are kept on errors only with WithProviderDiagnostics, and are then reachable only through (*CallError).Diagnostics.

Personal data and permitted use

Requests and results hold personal data. The SDK never logs, prints, stores or caches anything, and never reads credentials or configuration from the environment, but its request and result types have no redacting formatter: access control, logging, retention, security and permitted use are the caller's responsibility. Serializing or hashing personal data does not anonymize it. Person Search results also describe other people (relatives, associates and neighbors) and keep members the SDK does not decode as raw JSON, which prints in full.

A result is the provider's observation, not identity verification: no match, candidate, label, score, indicator or flag establishes anyone's identity, consent or eligibility for any purpose.

The provider's terms restrict how its data may be used. In summary, and without any claim of legal suitability: it is not a consumer reporting agency under the FCRA, so its data may not be used as a factor in eligibility for credit, insurance, employment, housing or any other FCRA purpose; results may not be stored or cached to make additional inquiries, merged with other data, scraped or resold; minors, celebrities and public figures may not be searched; and compliance with CAN-SPAM, the TCPA and Do Not Call rules is the caller's responsibility, as the provider scrubs no numbers. Read the provider's current terms before use.

Proxies

The default transport honors HTTPS_PROXY and NO_PROXY through http.ProxyFromEnvironment, as the standard library's default transport does. To bypass proxies, inject an http.Client whose transport sets no Proxy.

Scope and extension

Standard Contact Enrichment and Person Search are implemented. Contact Enrich Plus, Caller ID, ID Verification, the separate Reverse Phone Search API, batch requests, automatic paging and every other EnformionGO product are out of scope. Future operations would be added as new methods on Client, each with its own request and result types, without breaking existing callers.

Example (Fake)

Example_fake shows an application test 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-enformion"
)

// exContactEnricher is the small interface an application owns, so that its
// tests can use a fake instead of the provider.
type exContactEnricher interface {
	EnrichContact(ctx context.Context, req enformion.EnrichContactRequest) (*enformion.EnrichContactResult, error)
}

// exFakeEnricher is an application's test fake.
type exFakeEnricher struct {
	res *enformion.EnrichContactResult
	err error
}

func (f *exFakeEnricher) EnrichContact(context.Context, enformion.EnrichContactRequest) (*enformion.EnrichContactResult, error) {
	return f.res, f.err
}

func main() {
	var e exContactEnricher = &exFakeEnricher{
		err: &enformion.CallError{Kind: enformion.FailureRateLimited, StatusCode: http.StatusTooManyRequests},
	}
	_, err := e.EnrichContact(context.Background(), enformion.EnrichContactRequest{})
	fmt.Println(errors.Is(err, enformion.ErrRateLimited))
	fmt.Println(err)
}
Output:
true
enformion: rate_limited (HTTP 429)
Example (HttpHandler)

Example_httpHandler wires the handler into a server. It is compiled but never run.

package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"time"

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

// exContactEnricher is the small interface an application owns, so that its
// tests can use a fake instead of the provider.
type exContactEnricher interface {
	EnrichContact(ctx context.Context, req enformion.EnrichContactRequest) (*enformion.EnrichContactResult, error)
}

// exHandler is an application's HTTP handler that enriches a contact under the
// request's context and its own deadline, and logs only the error's kind and
// status.
type exHandler struct {
	enricher exContactEnricher
	log      *slog.Logger
}

// HandleEnrich answers with the provider's person, or 204 when the response
// carried none.
func (s *exHandler) HandleEnrich(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
	defer cancel()
	res, err := s.enricher.EnrichContact(ctx, enformion.EnrichContactRequest{
		FirstName: r.FormValue("first_name"),
		LastName:  r.FormValue("last_name"),
		Email:     r.FormValue("email"),
		Phone:     r.FormValue("phone"),
	})
	if err != nil {
		s.log.WarnContext(ctx, "contact enrichment failed", "error", err)
		status := exStatusFor(err)
		http.Error(w, http.StatusText(status), status)
		return
	}
	if res.Person == nil {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	if err = json.NewEncoder(w).Encode(res.Person); err != nil {
		s.log.WarnContext(ctx, "writing the enrichment response failed", "error", err)
	}
}

// exStatusFor maps an enrichment error onto the application's own status.
func exStatusFor(err error) int {
	switch {
	case errors.Is(err, enformion.ErrInvalidRequest):
		return http.StatusBadRequest
	case errors.Is(err, enformion.ErrRateLimited):
		return http.StatusTooManyRequests
	case errors.Is(err, enformion.ErrTimeout), errors.Is(err, context.DeadlineExceeded):
		return http.StatusGatewayTimeout
	}
	return http.StatusBadGateway
}

func main() {
	client, err := enformion.NewClient("example-key-name", "example-key-password")
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	h := &exHandler{enricher: client, log: slog.Default()}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /enrich", h.HandleEnrich)
	srv := &http.Server{Addr: "127.0.0.1:8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	_ = srv // in an application: srv.ListenAndServe()
}
Example (JsonRoundTrip)

Example_jsonRoundTrip shows that the SDK's own JSON keeps a false flag apart from an unreported one, and a zero score apart from an absent one.

package main

import (
	"encoding/json"
	"fmt"
	"reflect"

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

func main() {
	in := enformion.EnrichContactResult{
		IdentityScore: new(90),
		Person: &enformion.Person{Phones: []enformion.Phone{
			{Number: "(312) 555-0142", IsConnected: new(false)},
			{Number: "312-555-0199"},
		}},
	}
	b, err := json.Marshal(in)
	if err != nil {
		fmt.Println(err)
		return
	}
	var out enformion.EnrichContactResult
	if err = json.Unmarshal(b, &out); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reflect.DeepEqual(in, out))
	fmt.Println(*out.Person.Phones[0].IsConnected, out.Person.Phones[1].IsConnected == nil)
	fmt.Println(string(b))
}
Output:
true
false true
{"person":{"phones":[{"number":"(312) 555-0142","isConnected":false},{"number":"312-555-0199"}]},"identityScore":90}
Example (NoPerson)

Example_noPerson reads a response that carried no person data. The provider does not document what that means, so it is not proof that no match exists.

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

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

// exServer starts a local TLS server that answers every request with status
// and body. It stands in for the provider, so these examples run offline.
func exServer(status int, body string) *httptest.Server {
	return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_, _ = io.WriteString(w, body)
	}))
}

// exLocalClient returns a client pointed at a local test server.
func exLocalClient(srv *httptest.Server, opts ...enformion.Option) (*enformion.Client, error) {
	return enformion.NewClient("example-key-name", "example-key-password",
		append([]enformion.Option{
			enformion.WithTestBaseURL(srv.URL),
			enformion.WithHTTPClient(srv.Client()),
		}, opts...)...)
}

func main() {
	srv := exServer(http.StatusOK, `{"person": null, "message": "", "requestId": "synthetic-request-0003",
		"isError": false, "error": {"inputErrors": [], "warnings": ["Synthetic warning: no person was returned."]}}`)
	defer srv.Close()

	client, err := exLocalClient(srv)
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	res, err := client.EnrichContact(context.Background(), enformion.EnrichContactRequest{
		FirstName: "Riley", LastName: "Sample", Email: "riley.sample@example.com",
	})
	if err != nil {
		fmt.Println("enrich:", err)
		return
	}
	if res.Person == nil {
		fmt.Println("no person data in the response; not proof that no match exists")
	}
	fmt.Println("warnings:", len(res.Diagnostics.Warnings))
	fmt.Println(string(res.Diagnostics.Warnings[0]))
}
Output:
no person data in the response; not proof that no match exists
warnings: 1
"Synthetic warning: no person was returned."

Index

Examples

Constants

This section is empty.

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("enformion: invalid configuration")

	// ErrInvalidRequest reports a request that fails local validation, or a nil
	// context. No request was sent.
	ErrInvalidRequest = errors.New("enformion: invalid request")

	// ErrUnauthorized reports an HTTP 401 or 403 response: the provider refused
	// the credentials or the account's access.
	ErrUnauthorized = errors.New("enformion: unauthorized")

	// ErrRateLimited reports an HTTP 429 response, which the provider may use for
	// a rate limit or an exhausted monthly quota. The SDK never retries.
	ErrRateLimited = errors.New("enformion: rate limited")

	// ErrRejected reports a refused request: an HTTP 4xx status other than 401,
	// 403 and 429, or an HTTP 200 response whose envelope says isError: true.
	// A 404 is a rejection, never a "no match".
	ErrRejected = errors.New("enformion: rejected by provider")

	// ErrUpstream reports an HTTP 5xx response.
	ErrUpstream = errors.New("enformion: provider server error")

	// ErrUnexpectedResponse reports a response this SDK cannot interpret: a
	// status other than 200 outside the 4xx and 5xx ranges (including a 1xx,
	// another 2xx, a redirect, which is never followed, and anything from 600
	// on), a body that is not a JSON object, an isError flag that is missing or
	// not a boolean, a Person Search body without its persons member, or a
	// record whose only data is under keys this SDK does not decode: a Contact
	// Enrichment person, its name, or one of its address, phone or email
	// entries, or a Person Search person or one of its names, addresses,
	// phones, emails, locations, relatives, associates, dates of birth or
	// death records. The provider may already have processed and billed the
	// request.
	ErrUnexpectedResponse = errors.New("enformion: 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, or holds a
	// recognized field of the wrong JSON type. The provider may already have
	// processed and billed the request.
	ErrMalformedResponse = errors.New("enformion: malformed response")

	// ErrResponseTooLarge reports an HTTP 200 body larger than the configured
	// limit (see WithMaxResponseBytes), a decoded list with more than 1,000
	// entries, an SDK safety bound (the provider documents at most five per
	// Contact Enrichment person list), or a Person Search body that would
	// decode to more than four times its size plus 1 MiB, another SDK bound
	// that keeps a hostile response from costing many times its size in
	// memory. The provider may already have processed and billed the request.
	ErrResponseTooLarge = errors.New("enformion: response too large")

	// ErrTransport reports a failure in transit, such as DNS, connection, TLS or
	// proxy errors, a reset, or a truncated body. The request may or may not have
	// reached the provider, which may have processed and billed it.
	ErrTransport = errors.New("enformion: transport failure")

	// ErrTimeout reports that the SDK's own timeout (WithTimeout) 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
	// and billed the request.
	ErrTimeout = errors.New("enformion: timeout")
)

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, and for those the provider may already have processed, and billed, the request.

Functions

This section is empty.

Types

type Address

type Address struct {
	Street            string `json:"street,omitempty"`
	Unit              string `json:"unit,omitempty"`
	City              string `json:"city,omitempty"`
	State             string `json:"state,omitempty"`
	Zip               string `json:"zip,omitempty"`
	FirstReportedDate string `json:"firstReportedDate,omitempty"`
	LastReportedDate  string `json:"lastReportedDate,omitempty"`
}

Address is one address the provider associates with the person. Zip and the dates are text.

type CallError

type CallError struct {
	// Kind classifies the failure.
	Kind FailureKind

	// StatusCode is the HTTP status, or 0 when no response was received.
	StatusCode int

	// RequestID is the provider's requestId from the response envelope, kept
	// only when it is 1 to 128 bytes of visible ASCII.
	RequestID string

	// Field is a dotted JSON path, such as "person.phones[1].isConnected", for
	// type and shape failures. It names a location, never a value.
	Field string
	// contains filtered or unexported fields
}

CallError describes a call that was attempted, or that a canceled or expired context stopped before it was sent.

Its Error text is built only from Kind, StatusCode and Field: it never holds credentials, request values, URLs, headers, response bodies or provider messages, so it is safe to log. GoString and every fmt verb add only the provider's RequestID: 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 classifies failures with errors.Is. Error strings hold only the kind, the HTTP status and a field path, so they are safe to log; provider text is reachable only through Diagnostics, after WithProviderDiagnostics.

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

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

// exServer starts a local TLS server that answers every request with status
// and body. It stands in for the provider, so these examples run offline.
func exServer(status int, body string) *httptest.Server {
	return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_, _ = io.WriteString(w, body)
	}))
}

// exLocalClient returns a client pointed at a local test server.
func exLocalClient(srv *httptest.Server, opts ...enformion.Option) (*enformion.Client, error) {
	return enformion.NewClient("example-key-name", "example-key-password",
		append([]enformion.Option{
			enformion.WithTestBaseURL(srv.URL),
			enformion.WithHTTPClient(srv.Client()),
		}, opts...)...)
}

func main() {
	limited := exServer(http.StatusTooManyRequests, `{}`)
	defer limited.Close()
	rejecting := exServer(http.StatusBadRequest, `{"isError": true,
		"message": "Synthetic: Phone is not a valid number.",
		"error": {"inputErrors": [{"field": "Phone"}], "warnings": []}}`)
	defer rejecting.Close()

	for _, srv := range []*httptest.Server{limited, rejecting} {
		client, err := exLocalClient(srv, enformion.WithProviderDiagnostics())
		if err != nil {
			fmt.Println("config:", err)
			return
		}
		_, err = client.EnrichContact(context.Background(), enformion.EnrichContactRequest{
			FirstName: "Riley", LastName: "Sample", Phone: "(312) 555-0142",
		})
		ce, _ := errors.AsType[*enformion.CallError](err)
		switch {
		case errors.Is(err, context.Canceled):
			fmt.Println("canceled: the call may already have been billed")
		case errors.Is(err, enformion.ErrTimeout): // check before context.DeadlineExceeded
			fmt.Println("SDK timeout")
		case errors.Is(err, context.DeadlineExceeded):
			fmt.Println("caller deadline")
		case errors.Is(err, enformion.ErrUnauthorized):
			fmt.Println("check the API key:", ce.StatusCode)
		case errors.Is(err, enformion.ErrRateLimited):
			fmt.Println("rate limit or monthly quota; the SDK never retries:", ce.StatusCode)
		case errors.Is(err, enformion.ErrRejected):
			d := ce.Diagnostics() // may echo personal data: inspect, don't log
			fmt.Println("rejected:", ce.StatusCode, d.Message, len(d.InputErrors))
		case errors.Is(err, enformion.ErrMalformedResponse), errors.Is(err, enformion.ErrUnexpectedResponse):
			fmt.Println("unreadable response at", ce.Field, "(it may have been billed)")
		}
		fmt.Println("log line:", err)
	}
}
Output:
rate limit or monthly quota; the SDK never retries: 429
log line: enformion: rate_limited (HTTP 429)
rejected: 400 Synthetic: Phone is not a valid number. 1
log line: enformion: rejected (HTTP 400)

func (*CallError) Diagnostics

func (e *CallError) Diagnostics() ProviderDiagnostics

Diagnostics returns a deep copy of the provider's message, inputErrors and warnings for this failure. It is empty unless the Client was created with WithProviderDiagnostics. Provider text may echo the request's personal data: inspect it, but think before logging or storing it.

func (*CallError) Error

func (e *CallError) Error() string

Error returns "enformion: <kind>", followed by " (HTTP <status>)" when a status was received and ": <field>" when a field is named, such as "enformion: rate_limited (HTTP 429)".

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

type Client struct {
	// contains filtered or unexported fields
}

Client calls the EnformionGO developer APIs: Contact Enrichment (EnrichContact) and Person Search (SearchPersons). 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, across operations too.

Its fields are unexported and its credentials are held inside a function value, so formatting a Client, or a struct holding one, with any fmt verb or a reflection-based dumper never prints them.

func NewClient

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

NewClient returns a Client that authenticates with an EnformionGO API key.

Parameters:

  • keyName: the dashboard's API key name, sent as the galaxy-ap-name header
  • keyPassword: the dashboard's API key password, sent as galaxy-ap-password
  • opts: optional settings; see the With functions

Each credential must be 1 to 1024 bytes of printable ASCII (0x20 to 0x7E) without leading or trailing spaces. The application decides where they come 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 shows a production client. The application chooses where the credentials come from: the SDK never reads credentials from the environment or files. This example is compiled but never run, because every call to the provider is live and may be billed.

package main

import (
	"context"
	"fmt"
	"time"

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

func main() {
	var cfg struct {
		EnformionKeyName     string // the dashboard's API key name
		EnformionKeyPassword string // the dashboard's API key password
	}
	client, err := enformion.NewClient(cfg.EnformionKeyName, cfg.EnformionKeyPassword,
		enformion.WithTimeout(10*time.Second),
		enformion.WithMaxResponseBytes(512<<10),
	)
	if err != nil {
		fmt.Println("enformion config:", err) // never quotes the credentials
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	res, err := client.EnrichContact(ctx, enformion.EnrichContactRequest{
		FirstName: "Riley",
		LastName:  "Sample",
		Email:     "riley.sample@example.com",
		SessionID: "batch-7f3a9c-0001",
	})
	if err != nil {
		fmt.Println("enrich:", err) // kind, status and field path only
		return
	}
	fmt.Println(res.Person != nil)
}

func (*Client) EnrichContact

func (c *Client) EnrichContact(ctx context.Context, req EnrichContactRequest) (*EnrichContactResult, error)

EnrichContact sends one subject to the EnformionGO Contact Enrichment API, POST https://devapi.enformion.com/Contact/Enrich, and returns the provider's top person match.

The steps, in order:

  • check the Client, ctx and every request field, then the search categories, failing with a *ValidationError and sending nothing
  • fail with a *CallError (canceled or deadline_exceeded), sending nothing, when ctx is already done
  • make exactly one POST attempt, bounded by the Client's timeout and ctx, including the read of the whole response body
  • classify the status, then strictly decode an HTTP 200 body

Parameters:

  • ctx: cancels the call and bounds it with its deadline
  • req: the subject; see EnrichContactRequest for the rules

Returns the result, or an error that is a *ValidationError (nothing was sent) or a *CallError. A nil Person in the result means the response carried no person data; it is not proof that no match exists.

Side effects: one live, potentially billable call. The provider's pricing pages say it charges per successful match. The SDK never retries, follows a redirect, polls or makes a follow-on call. After a timeout, cancellation, transport failure or unreadable response, the provider may already have processed and billed the request: the SDK cannot tell, so repeating the call may be billed again.

Example

ExampleClient_EnrichContact enriches one subject with two categories, name and email, and reads the provider's observation.

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strconv"
	"time"

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

// exMatchBody is a synthetic HTTP 200 response in the documented shape.
const exMatchBody = `{
  "person": {
    "personId": "G-1000000000000000042",
    "name": {"firstName": "Riley", "middleName": "Q", "lastName": "Sample"},
    "age": "41",
    "partialDob": "6/1985",
    "addresses": [
      {"street": "100 Sample Way", "unit": "", "city": "Exampleton", "state": "OH", "zip": "45000",
       "firstReportedDate": "3/2/2011", "lastReportedDate": "8/14/2025"}
    ],
    "phones": [
      {"number": "(312) 555-0142", "type": "mobile", "isConnected": true, "lastReportedDate": "9/30/2025"},
      {"number": "(312) 555-0199", "type": "landline"}
    ],
    "emails": [{"email": "riley.sample@example.com", "isValidated": true, "isBusiness": false}]
  },
  "message": "",
  "identityScore": 87,
  "requestId": "synthetic-request-0001",
  "isError": false,
  "error": {"inputErrors": [], "warnings": []}
}`

// exServer starts a local TLS server that answers every request with status
// and body. It stands in for the provider, so these examples run offline.
func exServer(status int, body string) *httptest.Server {
	return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_, _ = io.WriteString(w, body)
	}))
}

// exLocalClient returns a client pointed at a local test server.
func exLocalClient(srv *httptest.Server, opts ...enformion.Option) (*enformion.Client, error) {
	return enformion.NewClient("example-key-name", "example-key-password",
		append([]enformion.Option{
			enformion.WithTestBaseURL(srv.URL),
			enformion.WithHTTPClient(srv.Client()),
		}, opts...)...)
}

func main() {
	srv := exServer(http.StatusOK, exMatchBody)
	defer srv.Close()

	client, err := exLocalClient(srv, enformion.WithTimeout(10*time.Second))
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	res, err := client.EnrichContact(context.Background(), enformion.EnrichContactRequest{
		FirstName: "Riley",
		LastName:  "Sample",
		Email:     "riley.sample@example.com",
		SessionID: "batch-7f3a9c-0001",
	})
	if err != nil {
		fmt.Println("enrich:", err)
		return
	}
	if res.Person == nil {
		fmt.Println("no person data in the response") // not proof that no match exists
		return
	}
	p := res.Person
	fmt.Println(p.PersonID, p.Name.FirstName, p.Name.LastName, p.Age, p.PartialDOB)
	for _, ph := range p.Phones {
		connected := "not reported"
		if ph.IsConnected != nil {
			connected = strconv.FormatBool(*ph.IsConnected) // not consent to contact
		}
		fmt.Printf("%s (%s) connected: %s\n", ph.Number, ph.Type, connected)
	}
	for _, a := range p.Addresses {
		fmt.Println(a.Street, a.City, a.State, a.Zip)
	}
	for _, e := range p.Emails {
		fmt.Println(e.Address, "validated:", e.IsValidated != nil && *e.IsValidated)
	}
	if res.IdentityScore != nil {
		fmt.Println("provider identityScore (uninterpreted):", *res.IdentityScore)
	}
	fmt.Println("request ID:", res.RequestID)
}
Output:
G-1000000000000000042 Riley Sample 41 6/1985
(312) 555-0142 (mobile) connected: true
(312) 555-0199 (landline) connected: not reported
100 Sample Way Exampleton OH 45000
riley.sample@example.com validated: true
provider identityScore (uninterpreted): 87
request ID: synthetic-request-0001

func (*Client) SearchPersons added in v0.2.0

func (c *Client) SearchPersons(ctx context.Context, req PersonSearchRequest) (*PersonSearchResult, error)

SearchPersons sends one Person Search page request to the EnformionGO Person Search API, POST https://devapi.enformion.com/PersonSearch, with the request's Mode as the search type, and returns the provider's candidates for that page.

The steps, in order:

  • check the Client, ctx and every request field, then the criteria, failing with a *ValidationError and sending nothing
  • fail with a *CallError (canceled or deadline_exceeded), sending nothing, when ctx is already done
  • make exactly one POST attempt, bounded by the Client's timeout and ctx, including the read of the whole response body, within the response limit (16 MiB unless WithMaxResponseBytes was given)
  • classify the status, then strictly decode an HTTP 200 body

Parameters:

  • ctx: cancels the call and bounds it with its deadline
  • req: the mode, criteria and page; see PersonSearchRequest for the rules

Returns the result, or an error that is a *ValidationError (nothing was sent) or a *CallError. A result without Persons means the response carried no candidates; it is not proof that no match exists. The candidates are the provider's, in its order: the SDK never selects, ranks or merges them.

Side effects: one live, potentially billable call for one page. Each page, and each change of mode, is a separate call that may be billed: the SDK never fetches a next page, upgrades a teaser search, retries, follows a redirect, polls or makes a follow-on call. After a timeout, cancellation, transport failure or unreadable response, the provider may already have processed and billed the request: the SDK cannot tell, so repeating the call may be billed again.

Example

ExampleClient_SearchPersons searches by name and reads the provider's candidates. The call returns one page and is a separate, potentially billable call; the SDK never selects a candidate for you.

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strconv"
	"time"

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

// exServer starts a local TLS server that answers every request with status
// and body. It stands in for the provider, so these examples run offline.
func exServer(status int, body string) *httptest.Server {
	return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_, _ = io.WriteString(w, body)
	}))
}

// exLocalClient returns a client pointed at a local test server.
func exLocalClient(srv *httptest.Server, opts ...enformion.Option) (*enformion.Client, error) {
	return enformion.NewClient("example-key-name", "example-key-password",
		append([]enformion.Option{
			enformion.WithTestBaseURL(srv.URL),
			enformion.WithHTTPClient(srv.Client()),
		}, opts...)...)
}

// exSearchBody is a synthetic HTTP 200 Person Search page.
const exSearchBody = `{
  "persons": [
    {
      "tahoeId": "G-1000000000000000101",
      "name": {"firstName": "Riley", "middleName": "Q", "lastName": "Sample"},
      "fullName": "Riley Q Sample",
      "age": 41,
      "locations": [{"city": "Exampleton", "state": "OH"}],
      "phoneNumbers": [
        {"phoneNumber": "(312) 555-0142", "phoneType": "Wireless", "isConnected": true},
        {"phoneNumber": "(312) 555-0199", "phoneType": "LandLine/Services"}
      ],
      "relativesSummary": [{"firstName": "Avery", "lastName": "Example", "relativeType": "Spouse"}],
      "driversLicenseDetail": []
    },
    {
      "tahoeId": "G-1000000000000000104",
      "name": {"firstName": "Riley", "lastName": "Sample", "suffix": "Jr"},
      "fullName": "Riley Sample Jr",
      "age": 19
    }
  ],
  "pagination": {"currentPageNumber": 1, "resultsPerPage": 10, "totalPages": 1, "totalResults": 2},
  "counts": {"searchResults": 2},
  "requestId": "synthetic-request-0201",
  "isError": false,
  "error": {"inputErrors": [], "warnings": []}
}`

func main() {
	srv := exServer(http.StatusOK, exSearchBody)
	defer srv.Close()

	client, err := exLocalClient(srv, enformion.WithTimeout(10*time.Second))
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	res, err := client.SearchPersons(context.Background(), enformion.PersonSearchRequest{
		Mode:           enformion.PersonSearchModePerson,
		FirstName:      "Riley",
		LastName:       "Sample",
		Addresses:      []enformion.PersonSearchRequestAddress{{AddressLine2: "Exampleton, OH"}},
		ResultsPerPage: 10,
		SessionID:      "batch-7f3a9c-0001",
	})
	if err != nil {
		fmt.Println("search:", err)
		return
	}
	if len(res.Persons) == 0 {
		fmt.Println("no candidates in the response") // not proof that no match exists
		return
	}
	for _, p := range res.Persons {
		age := "not reported"
		if p.Age != nil {
			age = strconv.Itoa(*p.Age)
		}
		fmt.Println(p.TahoeID, p.FullName, "age:", age)
		for _, ph := range p.PhoneNumbers {
			connected := "not reported"
			if ph.IsConnected != nil {
				connected = strconv.FormatBool(*ph.IsConnected) // not consent to contact
			}
			fmt.Printf("  %s (%s) connected: %s\n", ph.PhoneNumber, ph.PhoneType, connected)
		}
		for _, r := range p.RelativesSummary {
			fmt.Println("  relative:", r.FirstName, r.LastName, r.RelativeType) // the provider's label
		}
		for key := range p.Extra {
			fmt.Println("  undocumented member kept raw:", key)
		}
	}
	if pg := res.Pagination; pg.TotalPages != nil && pg.TotalResults != nil {
		fmt.Println("pages:", *pg.TotalPages, "results:", *pg.TotalResults)
	}
	fmt.Println("request ID:", res.RequestID)
}
Output:
G-1000000000000000101 Riley Q Sample age: 41
  (312) 555-0142 (Wireless) connected: true
  (312) 555-0199 (LandLine/Services) connected: not reported
  relative: Avery Example Spouse
  undocumented member kept raw: driversLicenseDetail
G-1000000000000000104 Riley Sample Jr age: 19
pages: 1 results: 2
request ID: synthetic-request-0201
Example (NextPage)

ExampleClient_SearchPersons_nextPage fetches a second page explicitly. The SDK never pages on its own: each page is a separate call that may be billed, so the application decides whether the next one is worth it.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"

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

// exLocalClient returns a client pointed at a local test server.
func exLocalClient(srv *httptest.Server, opts ...enformion.Option) (*enformion.Client, error) {
	return enformion.NewClient("example-key-name", "example-key-password",
		append([]enformion.Option{
			enformion.WithTestBaseURL(srv.URL),
			enformion.WithHTTPClient(srv.Client()),
		}, opts...)...)
}

func main() {
	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Page int `json:"Page"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		page := max(req.Page, 1)
		w.Header().Set("Content-Type", "application/json")
		_, _ = fmt.Fprintf(w, `{"persons": [{"tahoeId": "G-10000000000000003%02d", "fullName": "Jordan Placeholder %d"}],
			"pagination": {"currentPageNumber": %d, "resultsPerPage": 1, "totalPages": 2, "totalResults": 2},
			"isError": false}`, page, page, page)
	}))
	defer srv.Close()

	client, err := exLocalClient(srv)
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	req := enformion.PersonSearchRequest{
		Mode: enformion.PersonSearchModePerson, FirstName: "Jordan", LastName: "Placeholder", ResultsPerPage: 1,
	}
	for page := 1; page <= 2; page++ { // two pages, two billable calls
		req.Page = page
		res, err := client.SearchPersons(context.Background(), req)
		if err != nil {
			fmt.Println("search:", err)
			return
		}
		fmt.Println("page", *res.Pagination.CurrentPageNumber, "of", *res.Pagination.TotalPages, res.Persons[0].FullName)
	}
}
Output:
page 1 of 2 Jordan Placeholder 1
page 2 of 2 Jordan Placeholder 2
Example (ReversePhone)

ExampleClient_SearchPersons_reversePhone searches by phone number in the ReversePhonePerson mode, a mode of Person Search rather than the separate Reverse Phone Search API. The call is a separate, potentially billable call.

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

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

// exServer starts a local TLS server that answers every request with status
// and body. It stands in for the provider, so these examples run offline.
func exServer(status int, body string) *httptest.Server {
	return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_, _ = io.WriteString(w, body)
	}))
}

// exLocalClient returns a client pointed at a local test server.
func exLocalClient(srv *httptest.Server, opts ...enformion.Option) (*enformion.Client, error) {
	return enformion.NewClient("example-key-name", "example-key-password",
		append([]enformion.Option{
			enformion.WithTestBaseURL(srv.URL),
			enformion.WithHTTPClient(srv.Client()),
		}, opts...)...)
}

func main() {
	srv := exServer(http.StatusOK, `{"persons": [{"tahoeId": "G-1000000000000000101",
		"fullName": "Riley Q Sample", "phoneNumbers": [{"phoneNumber": "(312) 555-0142", "phoneOrder": 1}]}],
		"requestId": "synthetic-request-0202", "isError": false}`)
	defer srv.Close()

	client, err := exLocalClient(srv)
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	res, err := client.SearchPersons(context.Background(), enformion.PersonSearchRequest{
		Mode:  enformion.PersonSearchModeReversePhonePerson,
		Phone: "(312) 555-0142",
	})
	if err != nil {
		fmt.Println("search:", err)
		return
	}
	for _, p := range res.Persons {
		fmt.Println(p.TahoeID, p.FullName, len(p.PhoneNumbers))
	}
}
Output:
G-1000000000000000101 Riley Q Sample 1
Example (Teaser)

ExampleClient_SearchPersons_teaser makes a Teaser search, which the provider documents for "logged out" users, with most data masked or limited. The masking is the provider's: the SDK keeps every value verbatim. A Teaser call is still a separate call that may be billed, and the SDK never upgrades it to a Person search on its own.

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

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

// exServer starts a local TLS server that answers every request with status
// and body. It stands in for the provider, so these examples run offline.
func exServer(status int, body string) *httptest.Server {
	return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_, _ = io.WriteString(w, body)
	}))
}

// exLocalClient returns a client pointed at a local test server.
func exLocalClient(srv *httptest.Server, opts ...enformion.Option) (*enformion.Client, error) {
	return enformion.NewClient("example-key-name", "example-key-password",
		append([]enformion.Option{
			enformion.WithTestBaseURL(srv.URL),
			enformion.WithHTTPClient(srv.Client()),
		}, opts...)...)
}

func main() {
	srv := exServer(http.StatusOK, `{"persons": [{"tahoeId": "G-1000000000000000102", "fullName": "Avery E******",
		"locations": [{"city": "Exampleton", "state": "OH"}]}], "isError": false}`)
	defer srv.Close()

	client, err := exLocalClient(srv)
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	res, err := client.SearchPersons(context.Background(), enformion.PersonSearchRequest{
		Mode:           enformion.PersonSearchModeTeaser,
		FirstName:      "Avery",
		LastName:       "Example",
		Includes:       []enformion.PersonSearchInclude{enformion.PersonSearchIncludeAddresses},
		ResultsPerPage: 1,
	})
	if err != nil {
		fmt.Println("search:", err)
		return
	}
	p := res.Persons[0]
	fmt.Println(p.TahoeID, p.FullName, p.Locations[0].City)
}
Output:
G-1000000000000000102 Avery E****** Exampleton

type Email

type Email struct {
	Address     string `json:"email,omitempty"`
	IsValidated *bool  `json:"isValidated,omitempty"`
	IsBusiness  *bool  `json:"isBusiness,omitempty"`
}

Email is one email address the provider associates with the person.

IsValidated and IsBusiness are the provider's flags: nil means not reported. Neither is consent to contact the address.

type EnrichContactRequest

type EnrichContactRequest struct {
	// FirstName, MiddleName and LastName are sent as FirstName, MiddleName and
	// LastName. MiddleName may be a middle initial.
	FirstName  string
	MiddleName string
	LastName   string

	// DOB is the date of birth as mm/dd/yyyy, zero-padded, and must be a real
	// calendar date. It is sent as Dob.
	DOB string

	// Age is sent as Age when it is from 1 to 150; 0 means not sent.
	Age int

	// AddressLine1 is the house number and street name, or a PO Box.
	// AddressLine2 is the city and state, the state, or the ZIP code. They are
	// sent as Address.addressLine1 and Address.addressLine2.
	AddressLine1 string
	AddressLine2 string

	// Phone and Email are sent verbatim. The phone format is not enforced: the
	// provider's own examples disagree with its documented formats.
	Phone string
	Email string

	// SessionID is optional and sent as the galaxy-client-session-id header,
	// which the provider documents as a session ID for logging. It must be empty
	// or 1 to 128 bytes of visible ASCII (no spaces). Use an opaque value, never
	// personal data.
	SessionID string
}

EnrichContactRequest describes one subject to enrich.

The provider requires at least two of four search categories, and this SDK counts them as follows:

  • Name: FirstName and LastName both set (MiddleName alone, or a first or last name alone, is sent but does not count)
  • Phone
  • Email
  • Address: AddressLine1 or AddressLine2 set

DOB and Age are sent when set but are not categories.

Values are sent verbatim: the SDK never trims, normalizes or rewrites them. Every non-empty text field must be valid UTF-8 of at most 256 bytes, with no control characters (tabs included) and not only whitespace; these bounds are this SDK's own, as the provider documents none. The request is passed by value, and the SDK neither keeps nor modifies it.

The request holds personal data: see the package documentation.

type EnrichContactResult

type EnrichContactResult struct {
	// Person is the provider's top person match. It is nil when the response
	// carried no person data. The meaning of that is undocumented: it is not
	// proof that no match exists, and the SDK makes no claim about billing.
	Person *Person `json:"person,omitempty"`

	// IdentityScore is the provider's identityScore, an uninterpreted integer.
	// It is not a probability or a confidence. nil means the response had none;
	// a reported 0 is a pointer to 0.
	IdentityScore *int `json:"identityScore,omitempty"`

	// RequestID is the provider's requestId, kept only when present and 1 to 128
	// bytes of visible ASCII.
	RequestID string `json:"requestId,omitempty"`

	// Diagnostics holds the provider's message, inputErrors and warnings, if
	// any. They may echo the request's personal data.
	Diagnostics ProviderDiagnostics `json:"diagnostics,omitzero"`
}

EnrichContactResult is the provider's answer to one EnrichContact call.

It holds personal data the caller asked for: access control, logging, retention and permitted use are the caller's responsibility (see the package documentation). It has no redacting formatter.

The JSON tags give this SDK's own serialization, which round-trips: a result the SDK returned, marshaled and unmarshaled again, is reflect.DeepEqual to the original. It is not the provider's wire format.

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 (HTTP 401 or 403).
	FailureUnauthorized FailureKind = "unauthorized"

	// FailureRateLimited matches ErrRateLimited (HTTP 429).
	FailureRateLimited FailureKind = "rate_limited"

	// FailureRejected matches ErrRejected (another 4xx, or isError: true).
	FailureRejected FailureKind = "rejected"

	// FailureUpstream matches ErrUpstream (HTTP 5xx).
	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"
)

Failure kinds.

type Name

type Name struct {
	FirstName  string `json:"firstName,omitempty"`
	MiddleName string `json:"middleName,omitempty"`
	LastName   string `json:"lastName,omitempty"`
}

Name is a person's name as the provider reports it.

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 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 and is never followed. A nil transport means http.DefaultTransport. hc itself is never modified.

The transport is trusted: it sees the credential headers and the personal data in each request, and it may retry on its own, which the SDK cannot prevent. A nil hc is rejected.

func WithMaxResponseBytes

func WithMaxResponseBytes(n int64) Option

WithMaxResponseBytes limits the response body, counted after any transport decompression; n must be from 1 byte to 16 MiB. Without it, the limit is 1 MiB for EnrichContact and 16 MiB for SearchPersons, whose pages can hold many people; with it, n applies to every operation. A larger HTTP 200 body fails with ErrResponseTooLarge, after the provider may already have billed the call.

func WithProviderDiagnostics

func WithProviderDiagnostics() Option

WithProviderDiagnostics keeps the provider's message, inputErrors and warnings on errors, reachable only through (*CallError).Diagnostics. They are off by default, because errors are routinely logged and passed on, and provider text may echo the request's personal data. Results always carry their diagnostics.

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 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 credentials reach only the provider or loopback.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout bounds each call, including reading the whole response body. The default is 30 seconds; d must be greater than 0 and at most 5 minutes. The caller's context deadline applies as well.

type Person

type Person struct {
	PersonID   string    `json:"personId,omitempty"`
	Name       Name      `json:"name,omitzero"`
	Age        string    `json:"age,omitempty"`
	PartialDOB string    `json:"partialDob,omitempty"`
	Addresses  []Address `json:"addresses,omitempty"`
	Phones     []Phone   `json:"phones,omitempty"`
	Emails     []Email   `json:"emails,omitempty"`
}

Person is the provider's top person match.

Every field is optional: the documentation's own examples disagree on which fields the standard tier returns. Strings are provider text, kept verbatim and never parsed: Age is text on the wire, and the documentation's examples show dates as M/D/YYYY without zero padding.

Collections keep the provider's order and every entry it returned, except JSON null elements, which are not entries. A collection of more than 1,000 entries fails the call with ErrResponseTooLarge, an SDK safety bound (the provider documents at most five). The SDK never deduplicates, truncates or ranks entries, picks a "preferred" one, or infers relationships. This is the provider's observation, not identity verification.

type PersonSearchAddress added in v0.2.0

type PersonSearchAddress struct {
	FullAddress         string `json:"fullAddress,omitempty"`
	HouseNumber         string `json:"houseNumber,omitempty"`
	StreetPreDirection  string `json:"streetPreDirection,omitempty"`
	StreetName          string `json:"streetName,omitempty"`
	StreetPostDirection string `json:"streetPostDirection,omitempty"`
	StreetType          string `json:"streetType,omitempty"`
	Unit                string `json:"unit,omitempty"`
	UnitType            string `json:"unitType,omitempty"`
	City                string `json:"city,omitempty"`
	State               string `json:"state,omitempty"`
	County              string `json:"county,omitempty"`
	Zip                 string `json:"zip,omitempty"`
	Zip4                string `json:"zip4,omitempty"`
	DPC                 string `json:"dpc,omitempty"`
	Latitude            string `json:"latitude,omitempty"`
	Longitude           string `json:"longitude,omitempty"`
	AddressHash         string `json:"addressHash,omitempty"`
	BldgCode            string `json:"bldgCode,omitempty"`
	UtilityCode         string `json:"utilityCode,omitempty"`
	PropertyIndicator   string `json:"propertyIndicator,omitempty"`

	FirstReportedDate   string `json:"firstReportedDate,omitempty"`
	LastReportedDate    string `json:"lastReportedDate,omitempty"`
	PublicFirstSeenDate string `json:"publicFirstSeenDate,omitempty"`
	TotalFirstSeenDate  string `json:"totalFirstSeenDate,omitempty"`

	IsPublic        *bool `json:"isPublic,omitempty"`
	IsDeliverable   *bool `json:"isDeliverable,omitempty"`
	IsMergedAddress *bool `json:"isMergedAddress,omitempty"`
	UnitCount       *int  `json:"unitCount,omitempty"`
	AddressOrder    *int  `json:"addressOrder,omitempty"`

	HighRiskMarker PersonSearchHighRiskMarker `json:"highRiskMarker,omitzero"`

	// PhoneNumbers are phone numbers the provider associates with the
	// address, as text.
	PhoneNumbers        []string `json:"phoneNumbers,omitempty"`
	AddressQualityCodes []string `json:"addressQualityCodes,omitempty"`

	// Neighbors and NeighborSummaryRecords have no documented structure, so
	// each entry is kept as raw JSON (see PersonSearchPerson.Extra for the
	// normalization). They describe other people.
	Neighbors              []json.RawMessage `json:"neighbors,omitempty"`
	NeighborSummaryRecords []json.RawMessage `json:"neighborSummaryRecords,omitempty"`

	SourceSummary json.RawMessage `json:"sourceSummary,omitempty"`
}

PersonSearchAddress is one address the provider associates with a person. Every string, ZIP codes, coordinates, the address hash and dates among them, is provider text, never parsed.

type PersonSearchAssociate added in v0.2.0

type PersonSearchAssociate struct {
	TahoeID    string `json:"tahoeId,omitempty"`
	Prefix     string `json:"prefix,omitempty"`
	FirstName  string `json:"firstName,omitempty"`
	MiddleName string `json:"middleName,omitempty"`
	LastName   string `json:"lastName,omitempty"`
	Suffix     string `json:"suffix,omitempty"`
	DOB        string `json:"dob,omitempty"`
	Score      *int   `json:"score,omitempty"`
}

PersonSearchAssociate is one entry of a person's associatesSummary list: the provider's summary of another person it associates with the candidate. Score is a provider value, not a probability.

type PersonSearchCounts added in v0.2.0

type PersonSearchCounts struct {
	Names                      *int  `json:"names,omitempty"`
	Addresses                  *int  `json:"addresses,omitempty"`
	Relatives                  *int  `json:"relatives,omitempty"`
	Associates                 *int  `json:"associates,omitempty"`
	DebtRecords                *int  `json:"debtRecords,omitempty"`
	DatesOfBirth               *int  `json:"datesOfBirth,omitempty"`
	DatesOfDeath               *int  `json:"datesOfDeath,omitempty"`
	DeathRecords               *int  `json:"deathRecords,omitempty"`
	PhoneNumbers               *int  `json:"phoneNumbers,omitempty"`
	ExpectedCount              *int  `json:"expectedCount,omitempty"`
	SearchResults              *int  `json:"searchResults,omitempty"`
	EmailAddresses             *int  `json:"emailAddresses,omitempty"`
	BusinessRecords            *int  `json:"businessRecords,omitempty"`
	EvictionRecords            *int  `json:"evictionRecords,omitempty"`
	ForeclosureRecords         *int  `json:"foreclosureRecords,omitempty"`
	ForeclosureV2Records       *int  `json:"foreclosureV2Records,omitempty"`
	SocialSecurityNumbers      *int  `json:"socialSecurityNumbers,omitempty"`
	ProfessionalLicenseRecords *int  `json:"professionalLicenseRecords,omitempty"`
	SearchResultsOverflow      *bool `json:"searchResultsOverflow,omitempty"`
}

PersonSearchCounts is the response's counts object: uninterpreted provider integers, such as how many search results or addresses it found. Each member is nil when not reported; a reported 0 is a pointer to 0. Members the SDK does not know are ignored.

type PersonSearchDateOfBirth added in v0.2.0

type PersonSearchDateOfBirth struct {
	Age           *int            `json:"age,omitempty"`
	SourceSummary json.RawMessage `json:"sourceSummary,omitempty"`
}

PersonSearchDateOfBirth is one entry of a person's datesOfBirth list.

type PersonSearchDeathRecord added in v0.2.0

type PersonSearchDeathRecord struct {
	IsDeceased    *bool           `json:"isDeceased,omitempty"`
	SourceSummary json.RawMessage `json:"sourceSummary,omitempty"`
}

PersonSearchDeathRecord is a person's deathRecords object. IsDeceased is the provider's flag, nil when not reported.

type PersonSearchEmail added in v0.2.0

type PersonSearchEmail struct {
	EmailAddress    string                      `json:"emailAddress,omitempty"`
	EmailOrdinal    *int                        `json:"emailOrdinal,omitempty"`
	IsPremium       *bool                       `json:"isPremium,omitempty"`
	NonBusiness     *int                        `json:"nonBusiness,omitempty"`
	EmailEngagement PersonSearchEmailEngagement `json:"emailEngagementData,omitzero"`
	SourceSummary   json.RawMessage             `json:"sourceSummary,omitempty"`
}

PersonSearchEmail is one email address the provider associates with a person.

NonBusiness is the provider's integer, 0 or 1 on the wire, kept as it is rather than converted to a boolean. No flag or engagement value is consent to contact the address.

type PersonSearchEmailEngagement added in v0.2.0

type PersonSearchEmailEngagement struct {
	IsBounce         *bool    `json:"isBounce,omitempty"`
	IsMatched        *bool    `json:"isMatched,omitempty"`
	IsGoodDomain     *bool    `json:"isGoodDomain,omitempty"`
	SendTime         *int     `json:"sendTime,omitempty"`
	EngagementScore  *int     `json:"engagementScore,omitempty"`
	Frequency        string   `json:"frequency,omitempty"`
	BestDayOfTheWeek string   `json:"bestDayOfTheWeek,omitempty"`
	BestTimeOfTheDay string   `json:"bestTimeOfTheDay,omitempty"`
	NAICS            []string `json:"naics,omitempty"`
	LastCheckDate    string   `json:"lastCheckDate,omitempty"`
	LastTouchDate    string   `json:"lastTouchDate,omitempty"`
}

PersonSearchEmailEngagement is an email's emailEngagementData object: the provider's engagement data, uninterpreted. EngagementScore is a provider value, not a probability. Dates and times are provider text. Members the SDK does not know are ignored.

type PersonSearchFilter added in v0.2.0

type PersonSearchFilter string

PersonSearchFilter is a token of the request's FilterOptions list. The provider enables filters per account. Each constant's comment quotes the provider's description, which for several filters contradicts the token's name: the SDK sends the token verbatim and does not interpret it. Any other token of 1 to 128 ASCII letters and digits may be sent as PersonSearchFilter("...").

const (
	// PersonSearchFilterDisableFirstNameSynonymMatching is documented as "This
	// filter enables exact name match on first name."
	PersonSearchFilterDisableFirstNameSynonymMatching PersonSearchFilter = "DisableFirstNameSynonymMatching"

	// PersonSearchFilterDisableSmartSearch is documented as "If smart search is
	// enabled when we get a not hit we begin dropping off low.* value criteria
	// in an attempt to get a hit."
	PersonSearchFilterDisableSmartSearch PersonSearchFilter = "DisableSmartSearch"

	// PersonSearchFilterIncludeEmptyFirstNameResults is documented as "This
	// filter will remove results where a first name is not present."
	PersonSearchFilterIncludeEmptyFirstNameResults PersonSearchFilter = "IncludeEmptyFirstNameResults"

	// PersonSearchFilterIncludeSevenDigitPhoneNumbers is documented as "This
	// filter will include phone numbers with no area code."
	PersonSearchFilterIncludeSevenDigitPhoneNumbers PersonSearchFilter = "IncludeSevenDigitPhoneNumbers"

	// PersonSearchFilterIncludeLowQualityAddresses is documented as "This filter
	// will remove any addresses that do not come from a validated source".
	PersonSearchFilterIncludeLowQualityAddresses PersonSearchFilter = "IncludeLowQualityAddresses"

	// PersonSearchFilterIncludeLatestRecordsOnly is documented as "When enabled
	// the system will only provide the most recent phone/address record."
	PersonSearchFilterIncludeLatestRecordsOnly PersonSearchFilter = "IncludeLatestRecordsOnly"

	// PersonSearchFilterEnableRemoveSingleCharNames is documented as "Filters
	// out first names that are only one character long".
	PersonSearchFilterEnableRemoveSingleCharNames PersonSearchFilter = "EnableRemoveSingleCharNames"

	// PersonSearchFilterEnableExactFirstNameMatch is documented as "Filters out
	// records where the first name is not an exact match".
	PersonSearchFilterEnableExactFirstNameMatch PersonSearchFilter = "EnableExactFirstNameMatch"

	// PersonSearchFilterEnableExactLastNameMatch is documented as "Filters out
	// records where the last name is not an exact match".
	PersonSearchFilterEnableExactLastNameMatch PersonSearchFilter = "EnableExactLastNameMatch"

	// PersonSearchFilterDisableNoDobs is documented as "Returns records with
	// partial DOB and filters out any records with no DOB. Default behavior is
	// to return whatever is present in the data."
	PersonSearchFilterDisableNoDobs PersonSearchFilter = "DisableNoDobs"
)

Person Search filter tokens, each documented.

type PersonSearchHighRiskMarker added in v0.2.0

type PersonSearchHighRiskMarker struct {
	IsHighRisk  *bool  `json:"isHighRisk,omitempty"`
	SIC         string `json:"sic,omitempty"`
	AddressType string `json:"addressType,omitempty"`
}

PersonSearchHighRiskMarker is an address's highRiskMarker object: the provider's flag and codes, uninterpreted.

type PersonSearchInclude added in v0.2.0

type PersonSearchInclude string

PersonSearchInclude is a token of the request's Includes list, which asks for parts of each person. The provider enables includes per account. Its includes page lists labels, such as "Phone Numbers", rather than tokens: only Addresses and PhoneNumbers appear as tokens in its documentation. Any other token of 1 to 128 ASCII letters and digits may be sent as PersonSearchInclude("...").

const (
	// PersonSearchIncludeAddresses is a documented token.
	PersonSearchIncludeAddresses PersonSearchInclude = "Addresses"

	// PersonSearchIncludePhoneNumbers is a documented token.
	PersonSearchIncludePhoneNumbers PersonSearchInclude = "PhoneNumbers"

	// PersonSearchIncludeEmailAddresses is not in the documentation; it has
	// been observed to be accepted.
	PersonSearchIncludeEmailAddresses PersonSearchInclude = "EmailAddresses"

	// PersonSearchIncludeDatesOfBirth is not in the documentation; it has been
	// observed to be accepted.
	PersonSearchIncludeDatesOfBirth PersonSearchInclude = "DatesOfBirth"

	// PersonSearchIncludeRelatives is not in the documentation; it has been
	// observed to be accepted.
	PersonSearchIncludeRelatives PersonSearchInclude = "Relatives"

	// PersonSearchIncludeRelativesSummary is not in the documentation; it has
	// been observed to be accepted.
	PersonSearchIncludeRelativesSummary PersonSearchInclude = "RelativesSummary"

	// PersonSearchIncludeAssociates is not in the documentation; it has been
	// observed to be accepted. It returns each associate as a full person,
	// which makes a page much larger.
	PersonSearchIncludeAssociates PersonSearchInclude = "Associates"
)

Person Search include tokens.

type PersonSearchIndicators added in v0.2.0

type PersonSearchIndicators struct {
	HasBankruptcyRecords           *int `json:"hasBankruptcyRecords,omitempty"`
	HasBusinessRecords             *int `json:"hasBusinessRecords,omitempty"`
	HasDivorceRecords              *int `json:"hasDivorceRecords,omitempty"`
	HasDomainsRecords              *int `json:"hasDomainsRecords,omitempty"`
	HasEvictionsRecords            *int `json:"hasEvictionsRecords,omitempty"`
	HasFEINRecords                 *int `json:"hasFeinRecords,omitempty"`
	HasForeclosuresRecords         *int `json:"hasForeclosuresRecords,omitempty"`
	HasJudgmentRecords             *int `json:"hasJudgmentRecords,omitempty"`
	HasLienRecords                 *int `json:"hasLienRecords,omitempty"`
	HasMarriageRecords             *int `json:"hasMarriageRecords,omitempty"`
	HasProfessionalLicenseRecords  *int `json:"hasProfessionalLicenseRecords,omitempty"`
	HasPropertyRecords             *int `json:"hasPropertyRecords,omitempty"`
	HasVehicleRegistrationsRecords *int `json:"hasVehicleRegistrationsRecords,omitempty"`
	HasWorkplaceRecords            *int `json:"hasWorkplaceRecords,omitempty"`
	HasDEARecords                  *int `json:"hasDeaRecords,omitempty"`

	// The documentation lists the indicators above; these have been observed
	// as well.
	HasPropertyV2Records     *int `json:"hasPropertyV2Records,omitempty"`
	HasForeclosuresV2Records *int `json:"hasForeclosuresV2Records,omitempty"`
	HasUCCRecords            *int `json:"hasUccRecords,omitempty"`
	HasDebtRecords           *int `json:"hasDebtRecords,omitempty"`
}

PersonSearchIndicators is a person's indicators object, returned with the Indicators include: the provider's integers for whether, or how many, records of each kind it holds about the person. They are uninterpreted: the documentation shows only 0 and 1, while counts above 1 have been observed. Each member is nil when not reported. Members the SDK does not know are ignored.

type PersonSearchLocation added in v0.2.0

type PersonSearchLocation struct {
	City  string `json:"city,omitempty"`
	State string `json:"state,omitempty"`
}

PersonSearchLocation is one entry of a person's locations list.

type PersonSearchMode added in v0.2.0

type PersonSearchMode string

PersonSearchMode is the Person Search search type, sent as the galaxy-search-type header. The provider documents four, quoted below; it documents no response difference between them beyond that text.

const (
	// PersonSearchModePerson is documented "for more detailed information
	// pertaining to the subjects", mainly for "logged in or paying" users.
	PersonSearchModePerson PersonSearchMode = "Person"

	// PersonSearchModeTeaser is documented for "logged out" users: "Most of the
	// data elements in a teaser search are masked and/or limited by the
	// quantity returned."
	PersonSearchModeTeaser PersonSearchMode = "Teaser"

	// PersonSearchModeReversePhonePerson is documented with the same text as
	// PersonSearchModePerson. It is a mode of Person Search, not the separate
	// Reverse Phone Search API.
	PersonSearchModeReversePhonePerson PersonSearchMode = "ReversePhonePerson"

	// PersonSearchModeReversePhonePersonTeaser is documented with the same text
	// as PersonSearchModeTeaser.
	PersonSearchModeReversePhonePersonTeaser PersonSearchMode = "ReversePhonePersonTeaser"
)

Person Search modes.

type PersonSearchName added in v0.2.0

type PersonSearchName struct {
	Prefix     string `json:"prefix,omitempty"`
	FirstName  string `json:"firstName,omitempty"`
	MiddleName string `json:"middleName,omitempty"`
	LastName   string `json:"lastName,omitempty"`
	Suffix     string `json:"suffix,omitempty"`

	// RawNames are the name's other spellings as the provider reports them.
	RawNames []string `json:"rawNames,omitempty"`

	PublicFirstSeenDate string `json:"publicFirstSeenDate,omitempty"`
	TotalFirstSeenDate  string `json:"totalFirstSeenDate,omitempty"`

	// SourceSummary has no documented structure and is kept as raw JSON (see
	// PersonSearchPerson.Extra for the normalization). nil means absent or
	// null. The same holds for every SourceSummary below.
	SourceSummary json.RawMessage `json:"sourceSummary,omitempty"`
}

PersonSearchName is a name of a person: the person's own, an AKA or a merged name.

type PersonSearchPagination added in v0.2.0

type PersonSearchPagination struct {
	CurrentPageNumber *int `json:"currentPageNumber,omitempty"`
	ResultsPerPage    *int `json:"resultsPerPage,omitempty"`
	TotalPages        *int `json:"totalPages,omitempty"`
	TotalResults      *int `json:"totalResults,omitempty"`
}

PersonSearchPagination is the response's pagination object. Each member is nil when not reported; a reported 0 is a pointer to 0.

type PersonSearchPerson added in v0.2.0

type PersonSearchPerson struct {
	TahoeID  string           `json:"tahoeId,omitempty"`
	Name     PersonSearchName `json:"name,omitzero"`
	FullName string           `json:"fullName,omitempty"`

	IsPublic             *bool  `json:"isPublic,omitempty"`
	IsPremium            *bool  `json:"isPremium,omitempty"`
	IsOptedOut           *bool  `json:"isOptedOut,omitempty"`
	IsEnterpriseOptedOut *bool  `json:"isEnterpriseOptedOut,omitempty"`
	HasAdditionalData    *bool  `json:"hasAdditionalData,omitempty"`
	OptOutDate           string `json:"optOutDate,omitempty"`
	EnterpriseOptOutDate string `json:"enterpriseOptOutDate,omitempty"`
	SparseFlag           *int   `json:"sparseFlag,omitempty"`

	// DOB and DOD are dates of birth and death as provider text, which may be
	// partial or masked.
	DOB string `json:"dob,omitempty"`
	DOD string `json:"dod,omitempty"`
	Age *int   `json:"age,omitempty"`

	// IsCurrentPropertyOwner is provider text, such as "Not Available", not a
	// boolean.
	IsCurrentPropertyOwner string `json:"isCurrentPropertyOwner,omitempty"`

	DatesOfBirth []PersonSearchDateOfBirth `json:"datesOfBirth,omitempty"`

	// DatesOfDeath entries have no documented structure, so each is kept as
	// raw JSON (see Extra for the normalization).
	DatesOfDeath []json.RawMessage       `json:"datesOfDeath,omitempty"`
	DeathRecords PersonSearchDeathRecord `json:"deathRecords,omitzero"`

	AKAs              []PersonSearchName      `json:"akas,omitempty"`
	MergedNames       []PersonSearchName      `json:"mergedNames,omitempty"`
	Locations         []PersonSearchLocation  `json:"locations,omitempty"`
	Addresses         []PersonSearchAddress   `json:"addresses,omitempty"`
	PhoneNumbers      []PersonSearchPhone     `json:"phoneNumbers,omitempty"`
	EmailAddresses    []PersonSearchEmail     `json:"emailAddresses,omitempty"`
	RelativesSummary  []PersonSearchRelative  `json:"relativesSummary,omitempty"`
	AssociatesSummary []PersonSearchAssociate `json:"associatesSummary,omitempty"`

	// Associates are associated people as full persons, which the provider
	// returns with the Associates include. They are decoded one level deep:
	// an associate's own associates, if any, are kept in its Extra.
	Associates []PersonSearchPerson `json:"associates,omitempty"`

	Indicators PersonSearchIndicators `json:"indicators,omitzero"`

	// Extra holds every member of the person this SDK does not decode, such
	// as driversLicenseDetail or relatives, by its key as sent, so that a
	// member the provider adds or leaves undocumented is never lost. JSON null
	// members are left out, and an empty map is nil.
	//
	// Each value is a copy of the provider's JSON, never aliasing the
	// response, normalized as encoding/json marshals a json.RawMessage
	// (compact, with <, >, &, U+2028 and U+2029 escaped) after any unpaired
	// UTF-16 surrogate escape is replaced by �. The SDK neither types nor
	// interprets these values: they are opaque, may hold sensitive personal
	// data, including other people's, and print in full when formatted. They
	// count toward the response limit and the decode budget.
	Extra map[string]json.RawMessage `json:"extra,omitempty"`
}

PersonSearchPerson is one candidate person.

Every field is optional, and which ones the provider fills depends on the mode and the account's includes; teaser modes are documented to mask or limit data. Strings are provider text, kept verbatim and never parsed: dates and IDs among them. Numbers and flags are pointers, nil when not reported. A flag, such as IsOptedOut, is the provider's, and none is consent or eligibility for any purpose.

Collections keep the provider's order and every entry it returned, except JSON null elements, which are not entries. A collection of more than 1,000 entries fails the call with ErrResponseTooLarge, an SDK safety bound. Empty collections are nil.

type PersonSearchPhone added in v0.2.0

type PersonSearchPhone struct {
	PhoneNumber string `json:"phoneNumber,omitempty"`
	Company     string `json:"company,omitempty"`
	Location    string `json:"location,omitempty"`
	PhoneType   string `json:"phoneType,omitempty"`
	Latitude    string `json:"latitude,omitempty"`
	Longitude   string `json:"longitude,omitempty"`

	FirstReportedDate   string `json:"firstReportedDate,omitempty"`
	LastReportedDate    string `json:"lastReportedDate,omitempty"`
	PublicFirstSeenDate string `json:"publicFirstSeenDate,omitempty"`
	TotalFirstSeenDate  string `json:"totalFirstSeenDate,omitempty"`

	IsConnected *bool `json:"isConnected,omitempty"`
	IsPublic    *bool `json:"isPublic,omitempty"`
	PhoneOrder  *int  `json:"phoneOrder,omitempty"`

	SourceSummary json.RawMessage `json:"sourceSummary,omitempty"`
}

PersonSearchPhone is one phone number the provider associates with a person.

IsConnected and IsPublic are the provider's flags: nil means not reported. Neither is consent to contact the number, and the provider does not scrub numbers against any Do Not Call registry.

type PersonSearchRelative added in v0.2.0

type PersonSearchRelative struct {
	TahoeID            string   `json:"tahoeId,omitempty"`
	Prefix             string   `json:"prefix,omitempty"`
	FirstName          string   `json:"firstName,omitempty"`
	MiddleName         string   `json:"middleName,omitempty"`
	LastName           string   `json:"lastName,omitempty"`
	Suffix             string   `json:"suffix,omitempty"`
	DOB                string   `json:"dob,omitempty"`
	RelativeLevel      string   `json:"relativeLevel,omitempty"`
	RelativeType       string   `json:"relativeType,omitempty"`
	City               string   `json:"city,omitempty"`
	State              string   `json:"state,omitempty"`
	Spouse             *int     `json:"spouse,omitempty"`
	Score              *int     `json:"score,omitempty"`
	SharedHouseholdIDs []string `json:"sharedHouseholdIds,omitempty"`
	IsPrivate          *bool    `json:"isPrivate,omitempty"`
	IsOptedOut         *bool    `json:"isOptedOut,omitempty"`
	IsDeceased         *bool    `json:"isDeceased,omitempty"`
}

PersonSearchRelative is one entry of a person's relativesSummary list: the provider's summary of another person it relates to the candidate.

RelativeType, RelativeLevel and Spouse are the provider's labels and values; the SDK infers no relationship. Score is a provider value, not a probability. The flags are the provider's, nil when not reported.

type PersonSearchRequest added in v0.2.0

type PersonSearchRequest struct {
	// Mode is the search type, sent as the galaxy-search-type header. It is
	// required and must be one of the PersonSearchMode constants.
	Mode PersonSearchMode

	// FirstName, MiddleName and LastName are sent as FirstName, MiddleName and
	// LastName. MiddleName may be a middle initial.
	FirstName  string
	MiddleName string
	LastName   string

	// AKAs are alternative names, sent as Akas. Their shape is unverified; see
	// PersonSearchRequestName.
	AKAs []PersonSearchRequestName

	// DOB is the date of birth as mm/dd/yyyy, zero-padded, and must be a real
	// calendar date. It is sent as Dob.
	DOB string

	// Age, AgeRangeMinAge and AgeRangeMaxAge are each sent when from 1 to 150;
	// 0 means not sent. The SDK does not check them against each other or
	// against AgeRange.
	Age            int
	AgeRangeMinAge int
	AgeRangeMaxAge int

	// AgeRange is an age range such as "30-40": one to three digits, a hyphen
	// and one to three digits, each number at most 150.
	AgeRange string

	// Addresses are sent as the Addresses list.
	Addresses []PersonSearchRequestAddress

	// Email and Phone are sent verbatim. The phone format is not enforced: the
	// provider documents ###-###-#### and (###)###-####, but its examples
	// elsewhere disagree.
	Email string
	Phone string

	// ClientIP is an IP address to search by, sent as ClientIp. It must be a
	// canonical dotted IPv4 address, such as "192.0.2.10". The provider types
	// the member as an integer while documenting the dotted format; the SDK
	// sends a string, which is unverified.
	ClientIP string

	// Relatives are names of relatives, sent as Relatives. Their shape is
	// unverified; see PersonSearchRequestName.
	Relatives []PersonSearchRequestName

	// TahoeIDs are provider person IDs, such as a result's TahoeID, sent as the
	// TahoeIds list. Whether the provider expects this list or a single
	// TahoeId member is unverified.
	TahoeIDs []string

	// FirstNameCharOffset and LastNameCharOffset are documented as Levenshtein
	// distances that filter records by first and last name. nil means not
	// sent; a pointer to 0 is sent as 0. Each must be from 0 to 256.
	FirstNameCharOffset *int
	LastNameCharOffset  *int

	// DOBFormat is documented to override the date format of returned dates of
	// birth, sent as DobFormat. It is sent verbatim.
	DOBFormat string

	// MaxAddressYears and MaxPhoneYears are documented to filter out addresses
	// and phone numbers older than that many years. nil means not sent; a
	// pointer to 0 is sent as 0. Each must be from 0 to 150.
	MaxAddressYears *int
	MaxPhoneYears   *int

	// Includes and FilterOptions are sent as the Includes and FilterOptions
	// lists, verbatim and in order. Each token must be 1 to 128 ASCII letters
	// and digits. The provider enables both per account.
	Includes      []PersonSearchInclude
	FilterOptions []PersonSearchFilter

	// Page is the page to return, from 1, and ResultsPerPage the number of
	// persons per page, from 1 to 1,000 (an SDK bound). 0 means not sent, and
	// the provider's default applies. Each page is a separate, potentially
	// billable call.
	Page           int
	ResultsPerPage int

	// SessionID is optional and sent as the galaxy-client-session-id header,
	// which the provider documents as a session ID for logging. It must be empty
	// or 1 to 128 bytes of visible ASCII (no spaces). Use an opaque value, never
	// personal data.
	SessionID string
}

PersonSearchRequest describes one Person Search page: the mode, the search criteria, the includes and filters, and the page.

Mode is required, and at least one criterion must be set: a name part, an AKA, DOB, an age field, an address, Email, Phone, ClientIP, a relative or a TahoeID. Includes, FilterOptions, the offsets, the year limits and the page fields refine a search but are not criteria. The SDK checks only these rules and the formats below: it does not decide which criteria a mode needs, which age field wins, or whether a filter applies.

Values are sent verbatim, in order, duplicates included: the SDK never trims, normalizes, deduplicates or rewrites them. Every non-empty text field must be valid UTF-8 of at most 256 bytes, with no control characters (tabs included) and not only whitespace, and each list holds at most 32 entries; these bounds are this SDK's own, as the provider documents none. A list entry whose fields are all empty is rejected as blank. The request is passed by value, and the SDK neither keeps nor modifies it or its slices.

The request holds personal data: see the package documentation.

type PersonSearchRequestAddress added in v0.2.0

type PersonSearchRequestAddress struct {
	AddressLine1 string
	AddressLine2 string
	County       string
}

PersonSearchRequestAddress is one entry of a request's Addresses list, sent as AddressLine1, AddressLine2 and County. AddressLine1 is the house number and street name, or a PO Box; AddressLine2 is the city and state, the state, or the ZIP code.

type PersonSearchRequestName added in v0.2.0

type PersonSearchRequestName struct {
	FirstName  string
	MiddleName string
	LastName   string
}

PersonSearchRequestName is one name of a request's AKAs or Relatives list. The provider types these lists as Name{} without defining it; the SDK sends each entry as an object with FirstName, MiddleName and LastName, the members of the response's names. That shape is unverified.

type PersonSearchResult added in v0.2.0

type PersonSearchResult struct {
	// Persons are the page's candidates. nil means the response's persons
	// list was null or empty.
	Persons []PersonSearchPerson `json:"persons,omitempty"`

	// Pagination is the provider's pagination object. Its member names are
	// inferred from the provider's other endpoints and unverified.
	Pagination PersonSearchPagination `json:"pagination,omitzero"`

	// Counts is the provider's counts object.
	Counts PersonSearchCounts `json:"counts,omitzero"`

	// RequestID is the provider's requestId, kept only when present and 1 to 128
	// bytes of visible ASCII.
	RequestID string `json:"requestId,omitempty"`

	// CriteriaType and SmartSearchStatistics are the provider's criteriaType
	// and smartSearchStatistics members, whose structure is undocumented, kept
	// as raw JSON (see PersonSearchPerson.Extra for the normalization). nil
	// means absent or null. They may echo the request's personal data.
	CriteriaType          json.RawMessage `json:"criteriaType,omitempty"`
	SmartSearchStatistics json.RawMessage `json:"smartSearchStatistics,omitempty"`

	// Diagnostics holds the provider's message, inputErrors and warnings, if
	// any. They may echo the request's personal data.
	Diagnostics ProviderDiagnostics `json:"diagnostics,omitzero"`
}

PersonSearchResult is one page of the provider's answer to a SearchPersons call.

It holds personal data the caller asked for, and often data about other people (relatives, associates, neighbors): access control, logging, retention and permitted use are the caller's responsibility (see the package documentation). It has no redacting formatter.

Persons are the provider's candidates, in its order and with any duplicates it sent. The SDK never selects, ranks, merges or deduplicates candidates, and a candidate is not identity verification. An empty page means only that the response carried no candidates.

The JSON tags give this SDK's own serialization, which round-trips: a result the SDK returned, marshaled and unmarshaled again, is reflect.DeepEqual to the original. It is not the provider's wire format.

type Phone

type Phone struct {
	Number            string `json:"number,omitempty"`
	Type              string `json:"type,omitempty"`
	IsConnected       *bool  `json:"isConnected,omitempty"`
	FirstReportedDate string `json:"firstReportedDate,omitempty"`
	LastReportedDate  string `json:"lastReportedDate,omitempty"`
}

Phone is one phone number the provider associates with the person.

IsConnected is the provider's flag: nil means not reported. It is not consent to contact the number, and the provider does not scrub numbers against any Do Not Call registry.

type ProviderDiagnostics

type ProviderDiagnostics struct {
	Message     string            `json:"message,omitempty"`
	InputErrors []json.RawMessage `json:"inputErrors,omitempty"`
	Warnings    []json.RawMessage `json:"warnings,omitempty"`
}

ProviderDiagnostics holds the provider's free-form notes about a call: the envelope's message and its error.inputErrors and error.warnings lists.

The structure of list entries is undocumented, so each entry is kept as JSON, whatever its type, normalized as encoding/json marshals a json.RawMessage: compact, with <, >, &, U+2028 and U+2029 escaped, and any unpaired UTF-16 surrogate escape replaced by \ufffd. Bounds: Message is cut to 1 KiB on a UTF-8 boundary; each list keeps at most 32 entries, each at most 4 KiB once normalized. Longer entries, entries past the 32nd and JSON null entries are dropped. Empty lists are nil.

Provider text may echo the request's personal data.

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, with a list index where it has one, such as "DOB", "Addresses[1].County" or "keyPassword", and Reason is a short fixed code, such as "invalid_format". Neither ever contains the rejected value.

Example

ExampleValidationError shows a request rejected locally, before anything is sent: a first name alone is not a complete name, so only one category (the phone) counts.

package main

import (
	"context"
	"errors"
	"fmt"

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

func main() {
	// A loopback address with no server: even a bug could not reach the provider.
	client, err := enformion.NewClient("example-key-name", "example-key-password",
		enformion.WithTestBaseURL("https://127.0.0.1:9"))
	if err != nil {
		fmt.Println("config:", err)
		return
	}
	_, err = client.EnrichContact(context.Background(), enformion.EnrichContactRequest{
		FirstName: "Riley",
		Phone:     "(312) 555-0142",
	})
	if ve, ok := errors.AsType[*enformion.ValidationError](err); ok {
		fmt.Println(ve.Field, ve.Reason)
	}
	fmt.Println(errors.Is(err, enformion.ErrInvalidRequest))
	fmt.Println(err)
}
Output:
request insufficient_categories
true
enformion: invalid request: request: insufficient_categories

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error returns the sentinel's message followed by the field and the reason, such as "enformion: invalid request: DOB: invalid_format".

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the sentinel, ErrInvalidConfig or ErrInvalidRequest.

Directories

Path Synopsis
internal
testutil
Package testutil holds the test plumbing go-enformion's tests share: testdata fixtures, HTTP fakes and a recording TLS server, 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-enformion's tests share: testdata fixtures, HTTP fakes and a recording TLS server, 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