This commit is contained in:
Anang Yusman 2026-01-27 18:37:08 +08:00
parent 42e856f068
commit 976b7bc021
1 changed files with 40 additions and 21 deletions

View File

@ -307,52 +307,71 @@ func (_i *productsService) Delete(id uint) (err error) {
return
}
func (_i *productsService) Viewer(c *fiber.Ctx) error {
// ambil full path setelah /viewer/
objectPath := strings.TrimPrefix(c.Params("*"), "/")
func (_i *productsService) Viewer(c *fiber.Ctx) (err error) {
filename := c.Params("filename")
if objectPath == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
// Find product by filename (repository will search using LIKE pattern)
result, err := _i.Repo.FindByThumbnailPath(filename)
if err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
"error": true,
"msg": "Invalid file path",
"msg": "Product file not found",
})
}
bucketName := _i.MinioStorage.Cfg.ObjectStorage.MinioStorage.BucketName
if result.ThumbnailPath == nil || *result.ThumbnailPath == "" {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
"error": true,
"msg": "Product thumbnail path not found",
})
}
ctx := context.Background()
bucketName := _i.MinioStorage.Cfg.ObjectStorage.MinioStorage.BucketName
objectName := *result.ThumbnailPath
_i.Log.Info().Str("timestamp", time.Now().
Format(time.RFC3339)).Str("Service:Resource", "Products:Viewer").
Interface("data", objectName).Msg("")
// Create minio connection
minioClient, err := _i.MinioStorage.ConnectMinio()
if err != nil {
return c.Status(500).JSON(fiber.Map{
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": true,
"msg": err.Error(),
})
}
obj, err := minioClient.GetObject(
context.Background(),
bucketName,
objectPath,
minio.GetObjectOptions{},
)
fileContent, err := minioClient.GetObject(ctx, bucketName, objectName, minio.GetObjectOptions{})
if err != nil {
return c.Status(404).JSON(fiber.Map{
_i.Log.Error().Str("timestamp", time.Now().
Format(time.RFC3339)).Str("Service:Resource", "Products:Viewer").
Interface("Error getting file", err).Msg("")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": true,
"msg": "Product file not found",
"msg": "Failed to retrieve file",
})
}
defer obj.Close()
defer fileContent.Close()
contentType := mime.TypeByExtension(filepath.Ext(objectPath))
// Determine Content-Type based on file extension
contentType := mime.TypeByExtension("." + getFileExtension(objectName))
if contentType == "" {
contentType = "application/octet-stream"
contentType = "application/octet-stream" // fallback if no MIME type matches
}
c.Set("Content-Type", contentType)
_, err = io.Copy(c.Response().BodyWriter(), obj)
if _, err := io.Copy(c.Response().BodyWriter(), fileContent); err != nil {
return err
}
return
}
func getFileExtension(filename string) string {
// split file name
parts := strings.Split(filename, ".")