-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
88 lines (69 loc) · 1.9 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
package hackerone
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"github.com/hashicorp/go-retryablehttp"
"github.com/kenjoe41/h1scope/pkg/options"
)
func processProgramsApiRequest(link string, opt options.Options) (*Programs, error) {
resBody, err := makeAPIRequest(link, opt)
if err != nil {
return nil, fmt.Errorf("error making AI HTTP request: %s", err)
}
programs, err := UnmarshalPrograms(resBody)
if err != nil {
return nil, err
}
return programs, nil
}
func processAPIRequest(link string, opt options.Options) (*Scope, error) {
resBody, err := makeAPIRequest(link, opt)
if err != nil {
return nil, fmt.Errorf("error making AI HTTP request: %s", err)
}
scope, err := Unmarshal(resBody)
if err != nil {
return nil, err
}
return scope, nil
}
func makeAPIRequest(link string, opt options.Options) ([]byte, error) {
client := retryablehttp.NewClient()
client.Logger = nil
req, _ := retryablehttp.NewRequest("GET", link, nil)
req.Header.Set("Accept", "application/json")
req.Header.Add("Authorization", "Basic "+basicAuth(opt))
resp, err := client.Do(req)
if err != nil {
return nil, err
}
resBody, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("client: could not read response body: %s", err)
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("non-2XX response from server: %s", err)
}
return resBody, nil
}
func basicAuth(opt options.Options) string {
auth := opt.Username + ":" + opt.Apikey
return base64.StdEncoding.EncodeToString([]byte(auth))
}
func Unmarshal(jsonBytes []byte) (*Scope, error) {
scope := new(Scope)
if err := json.Unmarshal(jsonBytes, &scope); err != nil {
return nil, err
}
return scope, nil
}
func UnmarshalPrograms(jsonBytes []byte) (*Programs, error) {
programs := new(Programs)
if err := json.Unmarshal(jsonBytes, &programs); err != nil {
return nil, err
}
return programs, nil
}