cache.go 735 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package image
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "icloudapp.cn/tools/util"
  6. fileObj "icloudapp.cn/tools/util/file"
  7. "os"
  8. "strings"
  9. )
  10. type Cache struct {
  11. Path string
  12. }
  13. func NewCache(path string) *Cache {
  14. return &Cache{Path: path}
  15. }
  16. // SetCache 设置缓存目录
  17. func (c *Cache) SetCache(path string) {
  18. c.Path = path
  19. }
  20. // CacheFile Cache 获取缓存文件名
  21. func (c *Cache) CacheFile(file string, format string) string {
  22. if !fileObj.IsDir(c.Path) {
  23. if err := os.Mkdir(c.Path, 0755); err != nil {
  24. panic(err.Error())
  25. }
  26. }
  27. if file == "" {
  28. file = util.RandomStr(10)
  29. }
  30. destName := fmt.Sprintf("%x", md5.Sum([]byte(file)))
  31. destFile := fmt.Sprintf("%s/%s.%s", c.Path, destName, strings.ToLower(format))
  32. return destFile
  33. }