Skip to content

Commit

Permalink
feat: extract cache path logic into a separate function and update fi…
Browse files Browse the repository at this point in the history
…le path handling with MIME type extension
  • Loading branch information
krau committed Feb 27, 2025
1 parent 06d7c07 commit 2976097
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
10 changes: 7 additions & 3 deletions common/http_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,15 @@ func initHttpClient() {

var cacheLocks sync.Map

func getCachePath(url string) string {
return filepath.Join(config.Cfg.Storage.CacheDir, "req", MD5Hash(url))
}

func DownloadWithCache(ctx context.Context, url string, client *req.Client) ([]byte, error) {
if client == nil {
client = Client
}
cachePath := filepath.Join(config.Cfg.Storage.CacheDir, "req", MD5Hash(url))
cachePath := getCachePath(url)

data, err := os.ReadFile(cachePath)
if err == nil {
Expand Down Expand Up @@ -67,7 +71,7 @@ func GetBodyReader(ctx context.Context, url string, client *req.Client) (io.Read
if client == nil {
client = Client
}
cachePath := filepath.Join(config.Cfg.Storage.CacheDir, "req", MD5Hash(url))
cachePath := getCachePath(url)
if file, err := os.Open(cachePath); err == nil {
return file, nil
}
Expand All @@ -94,7 +98,7 @@ func GetBodyReader(ctx context.Context, url string, client *req.Client) (io.Read
}

func GetReqCachedFile(url string) ([]byte, error) {
cachePath := filepath.Join(config.Cfg.Storage.CacheDir, "req", MD5Hash(url))
cachePath := getCachePath(url)
data, err := os.ReadFile(cachePath)
if err != nil {
return nil, err
Expand Down
5 changes: 4 additions & 1 deletion storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"sync"
"time"

"github.com/gabriel-vasile/mimetype"
"github.com/krau/ManyACG/common"
"github.com/krau/ManyACG/config"
"github.com/krau/ManyACG/errs"
Expand Down Expand Up @@ -57,7 +58,9 @@ func SaveAll(ctx context.Context, artwork *types.Artwork, picture *types.Picture
if err != nil {
return nil, err
}
filePath := filepath.Join(config.Cfg.Storage.CacheDir, common.MD5Hash(picture.Original))
mimeType := mimetype.Detect(originalBytes)

filePath := filepath.Join(config.Cfg.Storage.CacheDir, common.MD5Hash(picture.Original)) + mimeType.Extension()
if err := common.MkFile(filePath, originalBytes); err != nil {
return nil, err
}
Expand Down

0 comments on commit 2976097

Please sign in to comment.