1. 程式人生 > >golang 使用docker api 拉取docker registry中的映象

golang 使用docker api 拉取docker registry中的映象

package main

import (
	"github.com/docker/docker/api/types"
	"golang.org/x/net/context"
	"github.com/docker/docker/client"
	"encoding/base64"
	"encoding/json"
	"io"
	"os"
	"fmt"
)

func PullImg(username,password,imgurl string) error {

	authConfig := types.AuthConfig{
		Username: username,
		Password: password,
	}
	encodedJSON, err := json.Marshal(authConfig)
	if err != nil {
		return err
	}
	authStr := base64.URLEncoding.EncodeToString(encodedJSON)

	ctx:= context.Background()
	cli,err := client.NewEnvClient()
	if err != nil {
		return err
	}

	reader, err := cli.ImagePull(ctx, imgurl, types.ImagePullOptions{RegistryAuth:authStr})
	if err != nil {
		return err
	}
	wr,err:=io.Copy(os.Stdout, reader)
	fmt.Println(wr)
	if err!=nil{
		return err
	}

	return nil
}

func main()  {

	PullImg("你的使用者名稱","你的密碼","dosec.io/alp:v1")
}