-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathapi.go
92 lines (76 loc) · 2.06 KB
/
api.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"golang.org/x/time/rate"
)
// This should ideally be store as an environment variable
const API_ENDPOINT = "http://data.moviebuff.com/"
// NewClient with a ratelimiter
func NewClient(rl *rate.Limiter) *HTTPClient {
c := &HTTPClient{
client: http.DefaultClient,
RateLimiter: rl,
}
return c
}
// A wrapper over client.Do() method for Rate limiting.
func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
err := c.RateLimiter.Wait(req.Context())
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
// Generic Function to Fetch Person|Movie Details
func FetchEntityDetails[T Entity](url string) (*T, error) {
req, err := http.NewRequest(http.MethodGet, API_ENDPOINT+url, nil)
if err != nil {
return nil, err
}
// Reduce the following limit in case of http.StatusTooManyRequests
rl := rate.NewLimiter(rate.Every(1*time.Second), 10000) // 10000 requests per second
client := NewClient(rl)
res, err := client.Do(req)
switch true {
case err != nil:
log.Println("Error occurred")
return nil, err
case res.StatusCode != http.StatusOK:
return nil, fmt.Errorf("%d: error occurred", res.StatusCode)
// In case of DoS prevention from the CDN, reduce the rate limit and try again
case res.StatusCode == http.StatusTooManyRequests:
log.Println("Reduce Rate Limit and Try Again!")
os.Exit(1)
}
var entity T
if err := json.NewDecoder(res.Body).Decode(&entity); err != nil {
return nil, err
}
defer res.Body.Close()
return &entity, nil
}
// Fetches the names of the persons and movie
func GetNames(parentURL string, personURL string, movieURL string) (string, string, string) {
parent, err := FetchEntityDetails[Person](parentURL)
if err != nil {
log.Println(err)
}
person, err := FetchEntityDetails[Person](personURL)
if err != nil {
log.Println(err)
}
movie, err := FetchEntityDetails[Movie](movieURL)
if err != nil {
log.Println(err)
}
return parent.Name, person.Name, movie.Name
}