/
push.go
59 lines (51 loc) · 1.16 KB
/
push.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
package image
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"os"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/registry"
"github.com/docker/docker/client"
)
// PushOption is the configuration for pushing an image
type PushOption struct {
Name string
Auth struct {
Username string
Password string
Server string
}
}
// Push pushes an image
func Push(cfg *PushOption) error {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Hour)
defer cancel()
auth := ""
if cfg.Auth.Username != "" && cfg.Auth.Password != "" {
authConfig := registry.AuthConfig{
Username: cfg.Auth.Username,
Password: cfg.Auth.Password,
ServerAddress: cfg.Auth.Server,
}
encodedJSON, err := json.Marshal(authConfig)
if err != nil {
return err
}
auth = base64.URLEncoding.EncodeToString(encodedJSON)
}
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
reader, err := cli.ImagePush(ctx, cfg.Name, types.ImagePushOptions{
RegistryAuth: auth,
})
if err != nil {
return err
}
io.Copy(os.Stdout, reader)
return nil
}