mlog-club内容图片地址更换
发布于
之前 https://mlog.club 的图片是放到七牛云的,后来 https://mlog.club 改用阿里云的oss来存储图片,所以使用阿里云oss的回源功能将七牛云的图片迁移到阿里云了,但是由于七牛云没有目录的概念,而且阿里云oss的回源功能又没法指定子目录,所以图片回源到oss之后全部放到根目录了,非常难受。所以我写了个方法将图片迁移到子目录中去。
先迁移图片
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/mlogclub/simple"
"strings"
)
func main() {
client, err := oss.New("endpoint", "ak", "sk")
if err != nil {
fmt.Println(err.Error())
panic(err)
}
bucket := oss.Bucket{Client: *client, BucketName: "mlogclub"}
list(bucket, "", func(objs []oss.ObjectProperties) {
var deleteObjects []string
for _, obj := range objs {
if strings.Index(obj.Key, "/") == -1 && simple.RuneLen(obj.Key) == 32 {
fmt.Println(obj.Key, simple.RuneLen(obj.Key))
_, err = bucket.CopyObject(obj.Key, "qiniu/"+obj.Key)
if err != nil {
fmt.Println("Error:", err)
}
deleteObjects = append(deleteObjects, obj.Key)
}
}
_, err = bucket.DeleteObjects(deleteObjects, oss.DeleteObjectsQuiet(true))
if err != nil {
fmt.Println("Error:", err)
}
})
}
type Callback func(objs []oss.ObjectProperties)
func list(bucket oss.Bucket, marker string, callback Callback) {
for {
ret, err := bucket.ListObjects(oss.MaxKeys(1000), oss.Marker(marker))
if err != nil {
fmt.Println(err.Error())
panic(err)
}
if len(ret.Objects) == 0 {
break
}
marker = ret.Objects[len(ret.Objects)-1].Key
callback(ret.Objects)
}
}
再更新内容
func (this *ArticleController) GetUpdate() *simple.JsonResult {
go func() {
services.ArticleService.Scan(func(articles []model.Article) bool {
for _, article := range articles {
newContent, update := replaceContentImg(article.Content)
if update {
logrus.Info("更新文章内容:" + strconv.FormatInt(article.Id, 10))
_ = services.ArticleService.UpdateColumn(article.Id, "content", newContent)
}
}
return true
})
services.TopicService.Scan(func(topics []model.Topic) {
for _, topic := range topics {
newContent, update := replaceContentImg(topic.Content)
if update {
logrus.Info("更新帖子内容:" + strconv.FormatInt(topic.Id, 10))
_ = services.TopicService.UpdateColumn(topic.Id, "content", newContent)
}
}
})
}()
return simple.JsonSuccess()
}
func replaceContentImg(content string) (string, bool) {
r, err := regexp.Compile("https://mlogclub.oss-cn-hongkong.aliyuncs.com/[a-z0-9]{32}")
if err == nil {
return r.ReplaceAllStringFunc(content, func(s string) string {
return strings.ReplaceAll(s, "https://mlogclub.oss-cn-hongkong.aliyuncs.com/", "https://mlogclub.oss-cn-hongkong.aliyuncs.com/qiniu/")
}), true
} else {
logrus.Error(err)
return content, false
}
}
浏览(549)
