forked from AfterShip/email-verifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgravatar.go
58 lines (53 loc) · 1.22 KB
/
gravatar.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
package emailverifier
import (
"context"
"io/ioutil"
"net/http"
"strings"
"time"
)
// Gravatar is detail about the Gravatar
type Gravatar struct {
HasGravatar bool // whether has gravatar
GravatarUrl string // gravatar url
}
// CheckGravatar will return the Gravatar records for the given email.
func (v *Verifier) CheckGravatar(email string) (*Gravatar, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err, emailMd5 := getMD5Hash(strings.ToLower(strings.TrimSpace(email)))
if err != nil {
return nil, err
}
gravatarUrl := gravatarBaseUrl + emailMd5 + "?d=404"
req, err := http.NewRequest("GET", gravatarUrl, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// check body
err, md5Body := getMD5Hash(string(body))
if err != nil {
return nil, err
}
if md5Body == gravatarDefaultMd5 || resp.StatusCode != 200 {
return &Gravatar{
HasGravatar: false,
GravatarUrl: "",
}, nil
}
return &Gravatar{
HasGravatar: true,
GravatarUrl: gravatarUrl,
}, nil
}