forked from vulncheck-oss/sdk
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
127 lines (104 loc) · 2.49 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package sdk
import (
"fmt"
"net/http"
"net/url"
"strings"
)
type Client struct {
Url string
Token string
HttpClient *http.Client
HttpRequest *http.Request
UserAgent string
Values *url.Values
FormValues *url.Values
}
type MetaError struct {
Error bool `json:"error"`
Errors []string `json:"errors"`
}
type ReqError struct {
StatusCode int
Reason MetaError
}
var ErrorUnauthorized = fmt.Errorf("unauthorized")
func Connect(url string, token string) *Client {
return &Client{Url: url, Token: token}
}
func (c *Client) GetToken() string {
return c.Token
}
func (c *Client) SetToken(token string) *Client {
c.Token = token
return c
}
func (c *Client) SetUrl(env string) *Client {
c.Url = env
return c
}
func (c *Client) GetUrl() string {
return c.Url
}
func (c *Client) SetUserAgent(userAgent string) *Client {
c.UserAgent = userAgent
return c
}
// SetAuthHeader Sets the Authorization header for the request
func (c *Client) SetAuthHeader(req *http.Request) *Client {
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+c.Token)
return c
}
func (c *Client) Request(method string, url string) (*http.Response, error) {
if c.HttpClient == nil {
c.HttpClient = &http.Client{}
}
var err error
if c.FormValues != nil {
c.HttpRequest, err = http.NewRequest(method, c.GetUrl()+url, strings.NewReader(c.FormValues.Encode()))
} else {
c.HttpRequest, err = http.NewRequest(method, c.GetUrl()+url, nil)
}
if err != nil {
return nil, err
}
c.SetAuthHeader(c.HttpRequest)
if c.UserAgent != "" {
c.HttpRequest.Header.Set("User-Agent", c.UserAgent)
}
if c.Values != nil {
c.HttpRequest.URL.RawQuery = c.Values.Encode()
}
if c.FormValues != nil {
c.HttpRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
resp, err := c.HttpClient.Do(c.HttpRequest)
if err != nil {
return nil, err
}
if resp.StatusCode == 401 {
return nil, ErrorUnauthorized
}
if resp.StatusCode != 200 {
return nil, handleErrorResponse(resp)
}
return resp, nil
}
func (c *Client) Query(key string, value string) *Client {
if c.Values == nil {
c.Values = &url.Values{}
}
c.Values.Add(key, value)
return c
}
func (c *Client) Form(key string, value string) *Client {
if c.FormValues == nil {
c.FormValues = &url.Values{}
}
c.FormValues.Add(key, value)
return c
}
func (e ReqError) Error() string {
return fmt.Sprintf("error: %t, status code: %d, errors: %v", e.Reason.Error, e.StatusCode, e.Reason.Errors)
}