Files
supermarket/internal/api/hunter/client.go
T
davidandClaude Opus 5.5 82d569da9c Phase 2 part 5: find people and verify emails with Hunter.io
Review gets Find people (Domain Search by the departments, seniority and
count set in Settings → Lead sources), Find their email (Email Finder for
a named person at a company), and Verify (one, or every unchecked address
in New). Every call is kept in enrich_runs (schema 9) with its result and
credits, and shown on the card. Nothing runs on a schedule. Sources are
shown by name (Hunter.io, origami.chat, explee.com).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 05:53:52 -07:00

278 lines
8.6 KiB
Go

// Package hunter finds and verifies work email addresses through Hunter.io's
// API (https://hunter.io/api-documentation/v2). Searches and verifications
// use the account's credits; the account call is free.
package hunter
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const apiBase = "https://api.hunter.io/v2"
var (
// ErrUnauthorized means the key was refused.
ErrUnauthorized = errors.New("Hunter.io refused the API key")
// ErrNoCredits means the plan's searches or verifications are used up.
ErrNoCredits = errors.New("Hunter.io says this month's credits are used up (HTTP 429)")
// ErrRateLimited means too many calls too quickly.
ErrRateLimited = errors.New("Hunter.io's rate limit was reached; try again in a minute")
)
// Client calls the API with one key.
type Client struct {
key, base string
http *http.Client
// Pause between polls of a verification that's still running.
poll time.Duration
}
func New(key string) *Client {
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: 40 * time.Second}, poll: 5 * time.Second}
}
// WithBase points the client at another server (for tests), and polls
// without waiting.
func (c *Client) WithBase(u string) *Client {
c.base = strings.TrimRight(u, "/")
c.poll = time.Millisecond
return c
}
// get calls path and decodes the response's "data" into out. It returns
// the credits the call used (the X-Credits-Used header) and the status.
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) (credits float64, status int, err error) {
u := c.base + path
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return 0, 0, err
}
req.Header.Set("X-API-KEY", c.key)
req.Header.Set("Accept", "application/json")
res, err := c.http.Do(req)
if err != nil {
return 0, 0, err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
if err != nil {
return 0, res.StatusCode, err
}
credits, _ = strconv.ParseFloat(res.Header.Get("X-Credits-Used"), 64)
switch res.StatusCode {
case http.StatusOK, http.StatusAccepted:
case http.StatusUnauthorized:
return 0, res.StatusCode, ErrUnauthorized
case http.StatusTooManyRequests:
return 0, res.StatusCode, ErrNoCredits
case http.StatusForbidden:
return 0, res.StatusCode, ErrRateLimited
default:
return credits, res.StatusCode, fmt.Errorf("Hunter.io %s: HTTP %d: %s", path, res.StatusCode, errorDetail(raw))
}
if res.StatusCode == http.StatusAccepted {
return credits, res.StatusCode, nil
}
var env struct {
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(raw, &env); err != nil {
return credits, res.StatusCode, fmt.Errorf("Hunter.io %s: %w", path, err)
}
if len(env.Data) == 0 || string(env.Data) == "null" {
return credits, res.StatusCode, nil
}
return credits, res.StatusCode, json.Unmarshal(env.Data, out)
}
// errorDetail is the first error's details, or the start of the body.
func errorDetail(raw []byte) string {
var e struct {
Errors []struct {
ID string `json:"id"`
Details string `json:"details"`
} `json:"errors"`
}
if json.Unmarshal(raw, &e) == nil && len(e.Errors) > 0 {
if e.Errors[0].Details != "" {
return e.Errors[0].Details
}
return e.Errors[0].ID
}
return strings.TrimSpace(string(raw[:min(len(raw), 300)]))
}
// Quota is what's left of one kind of request this period.
type Quota struct {
Used float64 `json:"used"`
Available float64 `json:"available"`
Remaining float64 `json:"remaining"`
}
// Account is the key owner's plan and what's left of it.
type Account struct {
Email string `json:"email"`
PlanName string `json:"plan_name"`
ResetDate string `json:"reset_date"`
Requests struct {
Credits *Quota `json:"credits"` // only on single-pool plans
Searches Quota `json:"searches"`
Verifications Quota `json:"verifications"`
} `json:"requests"`
}
// Left describes what's left, for the settings page.
func (a *Account) Left() string {
if q := a.Requests.Credits; q != nil {
return fmt.Sprintf("%s of %s credits left", num(q.Remaining), num(q.Available))
}
return fmt.Sprintf("%s of %s searches and %s of %s verifications left",
num(a.Requests.Searches.Remaining), num(a.Requests.Searches.Available),
num(a.Requests.Verifications.Remaining), num(a.Requests.Verifications.Available))
}
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
// Account checks the key. It costs nothing.
func (c *Client) Account(ctx context.Context) (*Account, error) {
var a Account
if _, _, err := c.get(ctx, "/account", nil, &a); err != nil {
return nil, err
}
return &a, nil
}
// Verification is Hunter's last check of an address.
type Verification struct {
Date string `json:"date"`
Status string `json:"status"` // valid, accept_all, unknown (invalid ones aren't returned)
}
// Email is a person Domain Search found.
type Email struct {
Value string `json:"value"`
Type string `json:"type"` // personal or generic
Confidence int `json:"confidence"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Position string `json:"position"`
Seniority string `json:"seniority"`
Department string `json:"department"`
DecisionMaker bool `json:"decision_maker"`
LinkedIn string `json:"linkedin"`
PhoneNumber string `json:"phone_number"`
Verification Verification `json:"verification"`
}
// DomainQuery says whom to look for at a domain.
type DomainQuery struct {
Domain string
Limit int // 1 to 100; on the free plan at most 10
Seniority []string // junior, senior, executive
Departments []string // executive, it, finance, management, sales, …
}
// DomainResult is what Domain Search found.
type DomainResult struct {
Organization string `json:"organization"`
Pattern string `json:"pattern"`
AcceptAll bool `json:"accept_all"`
Emails []Email `json:"emails"`
Credits float64 `json:"-"`
}
// DomainSearch finds people with personal addresses at a domain. It costs a
// search when anything is found.
func (c *Client) DomainSearch(ctx context.Context, q DomainQuery) (*DomainResult, error) {
v := url.Values{"domain": {q.Domain}, "type": {"personal"}}
if q.Limit > 0 {
v.Set("limit", strconv.Itoa(q.Limit))
}
if len(q.Seniority) > 0 {
v.Set("seniority", strings.Join(q.Seniority, ","))
}
if len(q.Departments) > 0 {
v.Set("department", strings.Join(q.Departments, ","))
}
var out DomainResult
credits, _, err := c.get(ctx, "/domain-search", v, &out)
out.Credits = credits
if err != nil {
return nil, err
}
return &out, nil
}
// Found is the address Email Finder found for a person.
type Found struct {
Email string `json:"email"`
Score int `json:"score"`
Position string `json:"position"`
LinkedInURL string `json:"linkedin_url"`
PhoneNumber string `json:"phone_number"`
Verification Verification `json:"verification"`
Credits float64 `json:"-"`
}
// FindEmail looks for a person's address at a domain. It costs a search
// only when an address is found; Email is "" otherwise.
func (c *Client) FindEmail(ctx context.Context, domain, first, last string) (*Found, error) {
v := url.Values{"domain": {domain}}
if first != "" && last != "" {
v.Set("first_name", first)
v.Set("last_name", last)
} else {
v.Set("full_name", strings.TrimSpace(first+" "+last))
}
var out Found
credits, _, err := c.get(ctx, "/email-finder", v, &out)
out.Credits = credits
if err != nil {
return nil, err
}
return &out, nil
}
// Checked is the result of verifying an address.
type Checked struct {
Status string `json:"status"` // valid, invalid, accept_all, webmail, disposable, unknown
Score int `json:"score"`
Credits float64 `json:"-"`
}
// Verify checks whether an address receives mail. Hunter answers 202 while
// a check runs (up to about 20 seconds); Verify asks again until it's done,
// which is counted once.
func (c *Client) Verify(ctx context.Context, email string) (*Checked, error) {
var out Checked
for attempt := 0; ; attempt++ {
credits, status, err := c.get(ctx, "/email-verifier", url.Values{"email": {email}}, &out)
out.Credits += credits
if err != nil {
return nil, err
}
if status != http.StatusAccepted {
return &out, nil
}
if attempt >= 6 {
return nil, errors.New("Hunter.io is still checking " + email + "; try again later")
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(c.poll):
}
}
}