add minio and file upload
This commit is contained in:
BIN
internal/admin/.DS_Store
vendored
BIN
internal/admin/.DS_Store
vendored
Binary file not shown.
@@ -1,17 +1,25 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
minioUpload "online-back/pkg/minio"
|
||||
"online-back/pkg/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -20,6 +28,8 @@ const (
|
||||
tokenURL = "/token"
|
||||
profileURL = "/profile"
|
||||
branchUserURL = "/branch-users"
|
||||
fileUploadURL = "/file"
|
||||
fileURL = "/file/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
@@ -37,6 +47,9 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
|
||||
protected := router.Group("", appresult.JwtTokenCheck())
|
||||
protected.GET(profileURL, h.getProfile)
|
||||
protected.POST(fileUploadURL, h.fileUpload)
|
||||
protected.GET(fileURL, h.getFile)
|
||||
protected.DELETE(fileURL, h.deleteFile)
|
||||
|
||||
branchUserGroup := router.Group(branchUserURL, appresult.JwtTokenCheck())
|
||||
branchUserGroup.POST("", h.createBranchUser)
|
||||
@@ -239,3 +252,135 @@ func currentUserID(c *gin.Context) (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// fileUpload godoc
|
||||
// @Description file upload
|
||||
// @Tags file-upload
|
||||
//
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Param file formData file true "this is a test file"
|
||||
//
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /file [post]
|
||||
func (h *handler) fileUpload(c *gin.Context) {
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
minioCfg := config.GetConfig().Minio
|
||||
minioClient, ok := h.connectMinio(c, minioCfg)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := c.Request.Context()
|
||||
if err := ensureBucket(ctx, minioClient, minioCfg.Bucket); err != nil {
|
||||
h.logger.Errorf("ensure minio bucket failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
objectName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
|
||||
if _, err := minioClient.PutObject(ctx, minioCfg.Bucket, objectName, file, header.Size, minio.PutObjectOptions{ContentType: contentType}); err != nil {
|
||||
h.logger.Errorf("upload file to minio failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(objectName))
|
||||
}
|
||||
|
||||
// getFile godoc
|
||||
// @Description download file
|
||||
// @Tags file-upload
|
||||
// @Produce octet-stream
|
||||
// @Param id path string true "object name"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {file} binary
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /file/{id} [get]
|
||||
func (h *handler) getFile(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
minioCfg := config.GetConfig().Minio
|
||||
minioClient, ok := h.connectMinio(c, minioCfg)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
object, err := minioClient.GetObject(c.Request.Context(), minioCfg.Bucket, id, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
h.logger.Errorf("get object from minio failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
defer object.Close()
|
||||
|
||||
content, err := io.ReadAll(object)
|
||||
if err != nil {
|
||||
h.logger.Errorf("read object from minio failed: %v", err)
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
c.Data(http.StatusOK, http.DetectContentType(content), content)
|
||||
}
|
||||
|
||||
// deleteFile godoc
|
||||
// @Description remove file
|
||||
// @Tags file-upload
|
||||
// @Produce json
|
||||
// @Param id path string true "object name"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /file/{id} [delete]
|
||||
func (h *handler) deleteFile(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
minioCfg := config.GetConfig().Minio
|
||||
minioClient, ok := h.connectMinio(c, minioCfg)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if err := minioClient.RemoveObject(c.Request.Context(), minioCfg.Bucket, id, minio.RemoveObjectOptions{GovernanceBypass: true}); err != nil {
|
||||
h.logger.Errorf("remove object from minio failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("file removed"))
|
||||
}
|
||||
|
||||
// connectMinio opens a MinIO client, writing an error response and returning
|
||||
// ok=false if the connection fails so callers can bail out immediately.
|
||||
func (h *handler) connectMinio(c *gin.Context, cfg config.MinioConfig) (*minio.Client, bool) {
|
||||
client, err := minioUpload.Connect(cfg.Endpoint, cfg.AccessKey, cfg.SecretKey, cfg.UseSSL)
|
||||
if err != nil {
|
||||
h.logger.Errorf("minio connection failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return nil, false
|
||||
}
|
||||
return client, true
|
||||
}
|
||||
|
||||
func ensureBucket(ctx context.Context, client *minio.Client, bucket string) error {
|
||||
exists, err := client.BucketExists(ctx, bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
return client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user