-
Notifications
You must be signed in to change notification settings - Fork 199
/
docker_hub_api.go
85 lines (71 loc) · 2.13 KB
/
docker_hub_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
package docker_registry
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type dockerHubApi struct{}
func newDockerHubApi() dockerHubApi {
return dockerHubApi{}
}
func (api *dockerHubApi) deleteRepository(ctx context.Context, account, project, token string) (*http.Response, error) {
url := fmt.Sprintf(
"https://hub.docker.com/v2/repositories/%s/%s/",
account,
project,
)
resp, _, err := doRequest(ctx, http.MethodDelete, url, nil, doRequestOptions{
Headers: map[string]string{
"Accept": "application/json",
"Authorization": fmt.Sprintf("JWT %s", token),
},
AcceptedCodes: []int{http.StatusOK, http.StatusAccepted, http.StatusNoContent},
})
return resp, err
}
func (api *dockerHubApi) deleteTag(ctx context.Context, account, project, tag, token string) (*http.Response, error) {
url := fmt.Sprintf(
"https://hub.docker.com/v2/repositories/%s/%s/tags/%s/",
account,
project,
tag,
)
resp, _, err := doRequest(ctx, http.MethodDelete, url, nil, doRequestOptions{
Headers: map[string]string{
"Accept": "application/json",
"Authorization": fmt.Sprintf("JWT %s", token),
},
AcceptedCodes: []int{http.StatusOK, http.StatusAccepted, http.StatusNoContent},
})
return resp, err
}
func (api *dockerHubApi) getToken(ctx context.Context, username, password string) (string, *http.Response, error) {
url := "https://hub.docker.com/v2/users/login/"
body, err := json.Marshal(map[string]string{
"username": username,
"password": password,
})
if err != nil {
return "", nil, err
}
resp, respBody, err := doRequest(ctx, http.MethodPost, url, bytes.NewBuffer(body), doRequestOptions{
Headers: map[string]string{
"Content-Type": "application/json",
},
AcceptedCodes: []int{http.StatusOK, http.StatusAccepted},
})
if err != nil {
return "", resp, err
}
resBodyJson := map[string]interface{}{}
if err := json.Unmarshal(respBody, &resBodyJson); err != nil {
return "", resp, err
}
token, ok := resBodyJson["token"].(string)
if !ok || token == "" {
return "", resp, fmt.Errorf("unexpected docker hub api response body: %s", string(respBody))
}
return token, resp, nil
}