// // adapter_local.go // Copyright (C) 2022 tiglog // // Distributed under terms of the MIT license. // package storage import ( "fmt" "io" "mime/multipart" "os" "path/filepath" "time" ) type LocalStorage struct { rootDir string } func NewLocalStorage(dir string) *LocalStorage { return &LocalStorage{rootDir: dir} } func (s *LocalStorage) GetName() string { return "local" } func (s *LocalStorage) Upload(upfile *multipart.FileHeader) (string, error) { now := time.Now() path := fmt.Sprintf("%d/%d/%d", now.Year(), now.Month(), now.Day()) fp := filepath.Join(s.rootDir, path) if _, err := os.Stat(fp); err != nil { os.MkdirAll(fp, 0755) } outfp := filepath.Join(fp, upfile.Filename) fd, err := os.Create(outfp) if err != nil { return "", err } defer fd.Close() ifd, err := upfile.Open() if err != nil { return "", err } defer ifd.Close() io.Copy(fd, ifd) return filepath.Join(path, upfile.Filename), nil } func (s *LocalStorage) GetBaseDir() string { return s.rootDir } func (s *LocalStorage) GetFullPath(path string) string { return filepath.Join(s.GetBaseDir(), path) }