golang调用docker registry API

golang调用docker registry API

使用docker官方的封装的接口来操作镜像仓库,示例代码如下:

import (
	"context"
	"io"
	"net/http"

	"github.com/docker/distribution"

	"github.com/docker/distribution/reference"
	"github.com/docker/distribution/registry/client"
)

const (
	mediaType = "application/vnd.docker.distribution.manifest.v2+json"
)

var (
	registryHost string
)

func InitRegistryClient(host string) error {
	registryHost = host

	return distribution.RegisterManifestSchema(mediaType, nil)
}

// 列出仓库中所有包含可用tag的镜像
func listImages() ([]string, error) {
	registry, err := client.NewRegistry("http://"+registryHost, http.DefaultTransport)
	if err != nil {
		return nil, err
	}

	allImages := make([]string, 0)
	var last string
	for {
		images := make([]string, 1024)
		count, err := registry.Repositories(context.Background(), images, last)
		if err == io.EOF {
			allImages = append(allImages, images[:count]...)
			break
		} else if err != nil {
			return nil, err
		}

		last = images[count-1]
		allImages = append(allImages, images...)
	}

	realImages := make([]string, 0)
	for _, image := range allImages {
		tags, err := listImageTags(image)
		if err != nil {
			return nil, err
		}

		if len(tags) != 0 {
			realImages = append(realImages, image)
		}
	}
	return realImages, nil
}

// 列出指定镜像的tag
func listImageTags(imageName string) ([]string, error) {
	repo, err := newRepository(imageName)
	if err != nil {
		return nil, err
	}

	ctx := context.Background()
	tagService := repo.Tags(ctx)
	return tagService.All(ctx)
}

// 删除指定镜像名称和tag
func deleteImageWithTag(imageName, imageTag string) error {
	repo, err := newRepository(imageName)
	if err != nil {
		return err
	}

	ctx := context.Background()
	tagService := repo.Tags(ctx)
	desc, err := tagService.Get(ctx, imageTag)
	if err != nil {
		return err
	}

	manifestService, err := repo.Manifests(ctx, nil)
	if err != nil {
		return err
	}

	return manifestService.Delete(ctx, desc.Digest)
}

func newRepository(imageName string) (distribution.Repository, error) {
	ref, err := reference.Parse(imageName)
	if err != nil {
		return nil, err
	}

	return client.NewRepository(ref.(reference.Named), "http://"+registryHost, http.DefaultTransport)
}

你可能感兴趣的:(golang)