contented/storage.go

58 lines
1.4 KiB
Go

package contented
import (
"context"
"io"
"os"
"path/filepath"
"github.com/minio/minio-go/v7"
)
func (this *Server) ReadFile(ctx context.Context, fileHash string) (io.ReadSeekCloser, error) {
if this.opts.StorageType == STORAGE_LOCAL {
fh, err := os.Open(filepath.Join(this.opts.DataDirectory, fileHash))
return fh, err
} else if this.opts.StorageType == STORAGE_S3 {
obj, err := this.s3client.GetObject(ctx, this.opts.DataS3Options.Bucket, this.opts.DataS3Options.Prefix+fileHash, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
return obj, nil
} else {
panic("bad StorageType")
}
}
func (this *Server) SaveFile(ctx context.Context, fileHash string, srcLen int64, src io.Reader) error {
if this.opts.StorageType == STORAGE_LOCAL {
// Save file to disk
dest, err := os.OpenFile(filepath.Join(this.opts.DataDirectory, fileHash), os.O_CREATE|os.O_WRONLY, this.opts.FileMode())
if err != nil {
if os.IsExist(err) {
return nil // hash matches existing upload
}
return err // Real error
}
defer dest.Close()
_, err = io.CopyN(dest, src, int64(srcLen))
if err != nil {
return err
}
return nil
} else if this.opts.StorageType == STORAGE_S3 {
_, err := this.s3client.PutObject(ctx, this.opts.DataS3Options.Bucket, this.opts.DataS3Options.Prefix+fileHash, src, srcLen, minio.PutObjectOptions{})
return err
} else {
panic("bad StorageType")
}
}