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()
}
Output:
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 ¶
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") // 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 ¶
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 ¶
GoString prints the exported metadata only, so that %#v cannot reach the cause or the provider diagnostics.
func (*CallError) Is ¶
Is reports whether target is the sentinel for e.Kind. A timeout also matches context.DeadlineExceeded, a caller deadline matches context.DeadlineExceeded and a cancellation matches context.Canceled.
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 ¶
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)
}
Output:
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
- 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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
Source Files
¶
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. |
