文章标题 原创 翻译 转载 文章内容 有个web/upload目录下有许多图片,但是很多图片是测试时产生的在博客文章中并没有使用,所以写个小程序判断哪些图片没有用到然后删除。 # 步骤 1. 连接数据库 2. 读取目录下的所有图片 3. 根据图片名字在数据库中查找 4. 如果没有找到文章就删除图片 # 源码 ``` package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "io/ioutil" "log" "os" "path" ) var PostBaseFields = "id, _id, author, title, profile, pv, tags, type, created_at, updated_at" type Post struct { gorm.Model Id string `gorm:"column:_id"` Author string `gorm:"column:author"` Title string `gorm:"column:title"` Profile string `gorm:"column:profile"` Content string `gorm:"column:content"` Pv int `gorm:"column:pv"` Tags string `gorm:"column:tags"` Type int `gorm:"column:type"` } func main() { db, err := gorm.Open("mysql", "root:password@tcp(118.xxx.xxx.xxx:3306)/blog?charset=utf8&parseTime=true") if err != nil { log.Fatal(err) } const webDir = "/root/web/upload" files, err := ioutil.ReadDir(webDir) if err != nil { log.Fatal(err) } for _, file := range files { key := file.Name() var posts []Post err = db.Select(PostBaseFields).Where("content like ?", "%"+key+"%").Find(&posts).Error if err == nil && len(posts) == 0 { fmt.Println(key) os.Remove(path.Join(webDir, file.Name())) } } } ``` 文章类别 Python Mobile Android Java Shell Life Database Bug Windows IOS Tools Boost Node.js Mac Product Tips C/C++ Golang Javascript React Qt MQ MongoDB Design Web Linux LLM ChatGPT RAG AI 提交