/
client.go
100 lines (83 loc) 路 1.86 KB
/
client.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
95
96
97
98
99
100
package cri
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"go.uber.org/zap"
"gopkg.in/resty.v1"
)
const (
endpoint = "https://cri.epita.fr/api/v2"
)
// Client struct
type Client struct {
httpClient *resty.Client
}
// SearchUser in CRI
func (c *Client) SearchUser(email string) (*ProfileResult, error) {
zap.S().Info("Searching CRI user: ", email)
resp, err := c.httpClient.R().
Get(endpoint + "/users/search/?emails=" + email)
if err != nil {
return nil, err
}
var result ProfileSearchReq
err = json.Unmarshal([]byte(resp.Body()), &result)
if err != nil {
zap.S().Error(err)
return nil, err
}
if strings.Contains(result.Detail, "Request was throttled") {
fmt.Println(result.Detail)
time.Sleep(time.Second * 10)
// Retry
return c.SearchUser(email)
}
zap.S().Info("Fetched CRI user.")
zap.S().Info(result)
zap.S().Warn(string(resp.Body()))
if len(result.Results) == 0 {
return nil, errors.New("not found")
}
return &result.Results[0], err
}
// GetGroup from CRI
func (c *Client) GetGroup(groupSlug string) (*Group, error) {
zap.S().Info("Fetching CRI group...")
zap.S().Info(groupSlug)
resp, err := c.httpClient.R().
Get(endpoint + "/groups/" + groupSlug + "/")
if err != nil {
zap.S().Error(err)
return nil, err
}
var result Group
err = json.Unmarshal(resp.Body(), &result)
if err != nil {
return nil, err
}
if strings.Contains(result.Detail, "Request was throttled") {
fmt.Println(result.Detail)
time.Sleep(time.Second * 10)
// Retry
return c.GetGroup(groupSlug)
}
zap.S().Info("Fetched CRI group.")
return &result, err
}
// NewClient constructor
func NewClient(username string, password string, url *string) *Client {
var e string
if url == nil {
e = endpoint
} else {
e = *url
}
c := Client{
httpClient: resty.New().SetHostURL(e),
}
c.httpClient.SetBasicAuth(username, password)
return &c
}