给定字符串
```
content="<span class=""><img class="wscnph" src="https://static.images.net/202233142551646287375.jpg"><img class="wscnph" src="https://static.images.net/202233142551646287377.jpg"></span>"
```
使用正则匹配图片链接,然后上传图片到阿里云oss,获得图片的链接,然后替换字符串中图片的链接,如果给定的字符串中图片很多,怎样才能提高图片上传替换的速度
```
func Upload(url string) string {
// 创建OSSClient实例。
client, err := oss.New(Endpoint, key, AccessKeySecret)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
t1 := time.Now().Unix()
if ti1 != t1 { //如果时间戳不一样,那么归零
long = 0
}
ti1 = t1
long++
obj := fmt.Sprintf("article/%d%d.png", t1, long)
// 获取存储空间。
bucket, err := client.Bucket(BucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 上传Byte数组。
err = bucket.PutObject(obj, bytes.NewReader(ReadImgData(url)))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
return "https://" + BucketName + "." + Endpoint + "/" + obj
}
func RepImages(htmls string) string {
var imgRE = regexp.MustCompile(`<img[^>]+\bsrc=["']([^"']+)["']`)
imgs := imgRE.FindAllStringSubmatch(htmls, -1)
out := make([]string, len(imgs))
myImage := ""
resHtml := htmls
for i := range out {
if ! strings.HasPrefix(imgs[i][1], "https://static.images.net") {
myImage = Upload(imgs[i][1])
resHtml = strings.Replace(resHtml, imgs[i][1], myImage, -1)
out[i] = imgs[i][1]
fmt.Println(strconv.Itoa(i), out[i])
}
}
fmt.Println(resHtml)
return resHtml
}
func main() {
//a := BcryptHash("admin123$")
//fmt.Print(a)
content := "<span class=\"\"><img class=\"wscnph\" src=\"https://static.images.net/2022331359421646287182.jpg\"><img class=\"wscnph\" src=\"https://static.images.net/202233135942164628718777.jpg\"></span>"
RepImages(content)
}
```
更多评论
2楼 <a href="/user/RafaelShin" title="@RafaelShin">@RafaelShin</a>
伪代码
res := make(chan string)
wg := &sync.WaitGroup{}
for _, url := range imgs {
go func(url, wg) { defer wg.done 发起http请求, 发送给res
}
for xxx := range res { 拿到上传好的url 替换
wg.wait() close(res)
#3