Golang 获取 Docker 镜像仓库地址 - 以 CentOS 为例
要获取到'https://registry.hub.docker.com/_/centos/' 这个镜像仓库地址,可以使用 Go 语言中的 net/http 包来发送 HTTP 请求,并解析响应中的数据。
以下是一个示例代码,演示了如何获取该镜像仓库地址:
package main
import (
'fmt'
'io/ioutil'
'net/http'
'regexp'
)
func main() {
// 发送GET请求
resp, err := http.Get('https://registry.hub.docker.com/_/centos/')
if err != nil {
fmt.Println('请求失败:', err)
return
}
defer resp.Body.Close()
// 读取响应的内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println('读取响应失败:', err)
return
}
// 使用正则表达式提取镜像仓库地址
re := regexp.MustCompile(`(?i)href='(https://registry.hub.docker.com/r/_/centos/[^']+)'`)
matches := re.FindStringSubmatch(string(body))
if len(matches) < 2 {
fmt.Println('未找到镜像仓库地址')
return
}
// 输出镜像仓库地址
fmt.Println('镜像仓库地址:', matches[1])
}
该示例中使用了正则表达式来提取镜像仓库地址,正则表达式(?i)href='(https://registry.hub.docker.com/r/_/centos/[^']+)' 用于匹配形如href='https://registry.hub.docker.com/r/_/centos/xxxx' 的链接,其中 xxxx 是镜像仓库地址的一部分。
原文地址: https://www.cveoy.top/t/topic/fKnw 著作权归作者所有。请勿转载和采集!