泛艺舟
发布于

替换字符串中的图片链接,如何提升性能呢?

给定字符串

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)
}
浏览 (555)
点赞 (3)
收藏
全部评论
暂无数据