enformion

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 22 Imported by: 0

README

🔎  go-enformion

A small, standard-library-only Go client for EnformionGO Contact Enrichment.


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 calls one operation of the EnformionGO developer APIs (Enformion, LLC): standard Contact Enrichment, POST https://devapi.enformion.com/Contact/Enrich with the 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) as typed Go values, with every field optional and nothing invented.

The client is deliberately narrow and strict: 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.


📦 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 1 B to 16 MiB Limits the (decompressed) response body.
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.

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.

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, or a person, its name, or an address, phone or email entry 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, or a person address, phone or email list of more than 1,000 entries
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)

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

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

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
Limits and unverified assumptions

Built from the provider's 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.

Scope and extension

Only standard Contact Enrichment is implemented. Contact Enrich Plus, Person Search, Caller ID, ID Verification, criminal and background searches, batch, pagination and detail lookups are out of scope, and none is stubbed. A future operation would be 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 Contact Enrichment 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, 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: nomatch, validation and auth take 1 call each, casing takes 2.
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 four together need 5), 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.


⚡ 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 one operation of the EnformionGO developer APIs (Enformion, LLC): standard Contact Enrichment, POST https://devapi.enformion.com/Contact/Enrich with the search type DevAPIContactEnrich.

Create a Client with NewClient and the dashboard's API key name and password, then call EnrichContact with at least two of the four documented search categories: name, phone, email and address. The result holds the provider's top person match, if the response carried one, 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",
})

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

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

Only standard Contact Enrichment is implemented. Contact Enrich Plus, Person Search, Caller ID, ID Verification, batch, pagination 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, or a person, its name, or one of its address, phone or
	// email entries whose only data is under keys this SDK does not decode. 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), or a person address, phone or email
	// list with more than 1,000 entries, an SDK safety bound (the provider
	// documents at most five). 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 Contact Enrichment API. Create it with NewClient; the zero Client and a nil *Client return ErrInvalidConfig without any I/O. A Client is immutable and safe for concurrent use.

Its fields are unexported and 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

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. The default is 1 MiB; n must be from 1 byte to 16 MiB. 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 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, such as "DOB" 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