-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathharbor.go
72 lines (61 loc) · 1.44 KB
/
harbor.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
package harbor
import (
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"net/http"
)
type Client struct {
baseURL string
token string
}
func NewClient(config *Config) *Client {
return &Client{
baseURL: config.URL + "/api/v2.0",
token: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", config.Username, config.Password))),
}
}
func (c *Client) getJSON(url string, useToken bool) ([]byte, error) {
req, err := http.NewRequest("GET", c.baseURL+url, nil)
if err != nil {
return nil, err
}
req.Header.Add("accept", "application/json")
if useToken {
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", c.token))
}
return c.doRequest(req)
}
func (c *Client) getText(url string, useToken bool) ([]byte, error) {
req, err := http.NewRequest("GET", c.baseURL+url, nil)
if err != nil {
return nil, err
}
req.Header.Add("accept", "text/plain")
if useToken {
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", c.token))
}
return c.doRequest(req)
}
func (c *Client) doRequest(req *http.Request) ([]byte, error) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf("failed to close response body cleanly; %v", err)
}
}()
respData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New(string(respData))
}
return respData, nil
}