90 lines
2.1 KiB
Go
90 lines
2.1 KiB
Go
package minio
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"mime"
|
|
"net/url"
|
|
|
|
"go-socket/packages/globals"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
)
|
|
|
|
var minClient *minio.Client
|
|
|
|
var canonicalExt = map[string]string{
|
|
"image/jpeg": ".jpg",
|
|
"image/png": ".png",
|
|
"image/gif": ".gif",
|
|
"image/webp": ".webp",
|
|
"video/mp4": ".mp4",
|
|
"application/pdf": ".pdf",
|
|
}
|
|
|
|
func extensionFromContentType(ct string) string {
|
|
if ext, ok := canonicalExt[ct]; ok {
|
|
return ext
|
|
}
|
|
exts, err := mime.ExtensionsByType(ct)
|
|
if err != nil || len(exts) == 0 {
|
|
return ".unk"
|
|
}
|
|
return exts[0]
|
|
}
|
|
|
|
func GetKey(hash string, contentType string) string {
|
|
return hash + extensionFromContentType(contentType)
|
|
}
|
|
|
|
func Init() {
|
|
ctx := context.Background()
|
|
|
|
var err error
|
|
minClient, err = minio.New("localhost:9000", &minio.Options{
|
|
Creds: credentials.NewStaticV4("root", "change_to_env", ""),
|
|
Secure: false,
|
|
}) // TODO change in production
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
exists, err := minClient.BucketExists(ctx, globals.FileStorageBucketName)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
if !exists {
|
|
err = minClient.MakeBucket(ctx, globals.FileStorageBucketName, minio.MakeBucketOptions{})
|
|
if err != nil {
|
|
return
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func Upload(ctx context.Context, key string, body io.Reader, size int64, contentType string, id uuid.UUID) error {
|
|
_, err := minClient.PutObject(ctx, globals.FileStorageBucketName, key, body, size,
|
|
minio.PutObjectOptions{
|
|
ContentType: contentType,
|
|
PartSize: globals.FileProcessingPartSize,
|
|
NumThreads: globals.FileProcessingThreads,
|
|
UserMetadata: map[string]string{
|
|
"id": id.String(),
|
|
},
|
|
})
|
|
return err
|
|
}
|
|
|
|
func GetDownloadUrl(ctx context.Context, key string) (*url.URL, error) {
|
|
u, err := minClient.PresignedGetObject(ctx, globals.FileStorageBucketName, key, globals.FileDownloadLinkTtl, nil)
|
|
return u, err
|
|
}
|
|
|
|
func DoesExist(ctx context.Context, key string) bool {
|
|
_, err := minClient.StatObject(ctx, globals.FileStorageBucketName, key, minio.StatObjectOptions{})
|
|
return err == nil
|
|
}
|