Golang-Docker API-解析ImagePull的结果 [英] Golang - Docker API - parse result of ImagePull
问题描述
我正在开发一个 Go
脚本,该脚本使用 Docker API
用于我的项目.登录到存储库后,提取所需的Docker映像,但问题是 io.ReadCloser 的实例能够通过以下方式传递到系统输出:
I'm developing a Go
script that uses the Docker API
for the purposes of my project. After I login to my repository, I pull the Docker image I want, but the problem is that the ImagePull function returns an instance of io.ReadCloser, which I'm only able to pass to the system output via:
io.Copy(os.Stdout, pullResp)
我可以看到响应,这很酷,但是我找不到合适的方法来解析它并根据它执行逻辑,如果下载了新版本的图像,这将做一些事情,而其他图片是否为最新内容.
如果您遇到这样的问题,我会很高兴与您分享经验.
It's cool that I can see the response, but I can't find a decent way to parse it and implement a logic depending on it, which will do some things if a new version of the image have been downloaded, and other things if the image was up to date.
I'll be glad if you share your experience, if you have ever faced this problem.
推荐答案
@ radoslav-stoyanov在使用我的示例之前先做
@radoslav-stoyanov before use my example do
#docker rmi busybox
然后运行代码
package main
import (
"encoding/json"
"fmt"
"github.com/docker/distribution/context"
docker "github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
"io"
"strings"
)
func main() {
// DOCKER
cli, err := docker.NewClient("unix:///var/run/docker.sock", "v1.28", nil, map[string]string{"User-Agent": "engine-api-cli-1.0"})
if err != nil {
panic(err)
}
imageName := "busybox:latest"
events, err := cli.ImagePull(context.Background(), imageName, types.ImagePullOptions{})
if err != nil {
panic(err)
}
d := json.NewDecoder(events)
type Event struct {
Status string `json:"status"`
Error string `json:"error"`
Progress string `json:"progress"`
ProgressDetail struct {
Current int `json:"current"`
Total int `json:"total"`
} `json:"progressDetail"`
}
var event *Event
for {
if err := d.Decode(&event); err != nil {
if err == io.EOF {
break
}
panic(err)
}
fmt.Printf("EVENT: %+v\n", event)
}
// Latest event for new image
// EVENT: {Status:Status: Downloaded newer image for busybox:latest Error: Progress:[==================================================>] 699.2kB/699.2kB ProgressDetail:{Current:699243 Total:699243}}
// Latest event for up-to-date image
// EVENT: {Status:Status: Image is up to date for busybox:latest Error: Progress: ProgressDetail:{Current:0 Total:0}}
if event != nil {
if strings.Contains(event.Status, fmt.Sprintf("Downloaded newer image for %s", imageName)) {
// new
fmt.Println("new")
}
if strings.Contains(event.Status, fmt.Sprintf("Image is up to date for %s", imageName)) {
// up-to-date
fmt.Println("up-to-date")
}
}
}
您可以看到用于创建结构的API格式(例如我的 Event
)以在此处阅读它们
You can see API formats to create your structures (like my Event
) to read them here https://docs.docker.com/engine/api/v1.27/#operation/ImageCreate
我希望它能帮助您解决问题,谢谢.
I hope it helps you solve your problem, thanks.
这篇关于Golang-Docker API-解析ImagePull的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!