-
Notifications
You must be signed in to change notification settings - Fork 0
/
hunter.go
94 lines (77 loc) · 2.04 KB
/
hunter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package emailvalidator
import (
"encoding/json"
"io"
"net/http"
"net/url"
"path"
"github.com/r-goswami/email-validator/internal"
)
const (
defaultHunterAPIURL = "https://api.hunter.io"
defaultHunterAPIVersion = "/v2"
defaultEmailVerifierSubPath = "/email-verifier"
)
// HunterAPIClient defines http client for making Hunter's REST calls
type HunterAPIClient struct {
apiKey string
baseURL *url.URL
client *internal.HTTPClient
}
// NewHunterAPIClient creates new Hunter API client for calling Hunter's REST APIs
func NewHunterAPIClient(apiKey string, options ...HunterAPIOptionFunc) (*HunterAPIClient, error) {
if apiKey == "" {
return nil, ErrEmptyAPIKey
}
opts, err := parseHunterAPIOptions(options...)
if err != nil {
return nil, err
}
u, err := url.Parse(opts.baseURL.String())
if err != nil {
return nil, err
}
u.Path = path.Join(u.Path, opts.apiVersion)
clientOpts := []func(*internal.Option){
internal.WithLimit(opts.rate.Limit),
internal.WithLimitInterval(opts.rate.Interval),
}
if opts.blocking {
clientOpts = append(clientOpts, internal.WithBlocking())
}
client := internal.NewClient(clientOpts...)
return &HunterAPIClient{
apiKey: apiKey,
baseURL: u,
client: client,
}, nil
}
// Validate validates email address and returns hunter api's response
func (hc *HunterAPIClient) Validate(email string) (*HunterValidateEmailResp, error) {
// Add Query params
params := url.Values{}
params.Add("api_key", hc.apiKey)
params.Add("email", email)
hc.baseURL.RawQuery = params.Encode()
// Create HTTP Request
url := path.Join(hc.baseURL.Path, defaultEmailVerifierSubPath)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
// Make REST Call
resp, err := hc.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
validateResp := &HunterValidateEmailResp{}
if err = json.Unmarshal(body, validateResp); err != nil {
return nil, err
}
return validateResp, nil
}