upload.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // Package handlers
  2. package handlers
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "time"
  10. "github.com/google/uuid"
  11. "github.com/minio/minio-go/v7"
  12. "github.com/minio/minio-go/v7/pkg/credentials"
  13. )
  14. const maxUploadSize = 10 << 20 // 10 MB
  15. type UploadHandler struct {
  16. minioClient *minio.Client
  17. bucket string
  18. endpoint string
  19. publicEndpoint string
  20. }
  21. func NewUploadHandler(endpoint, publicEndpoint, accessKey, secretKey, bucket string, useSSL bool) (*UploadHandler, error) {
  22. client, err := minio.New(endpoint, &minio.Options{
  23. Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
  24. Secure: useSSL,
  25. })
  26. if err != nil {
  27. return nil, err
  28. }
  29. return &UploadHandler{
  30. minioClient: client,
  31. bucket: bucket,
  32. endpoint: endpoint,
  33. publicEndpoint: publicEndpoint,
  34. }, nil
  35. }
  36. type presignedURLRequest struct {
  37. ContentType string `json:"content_type"`
  38. MaxSizeMB int `json:"max_size_mb"`
  39. }
  40. type presignedURLResponse struct {
  41. UploadURL string `json:"upload_url"`
  42. FileURL string `json:"file_url"`
  43. Fields map[string]string `json:"fields"`
  44. }
  45. func (h *UploadHandler) UploadFile(w http.ResponseWriter, r *http.Request) {
  46. r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
  47. if err := r.ParseMultipartForm(maxUploadSize); err != nil {
  48. writeError(w, http.StatusBadRequest, "file too large or invalid multipart", err)
  49. return
  50. }
  51. file, header, err := r.FormFile("file")
  52. if err != nil {
  53. writeError(w, http.StatusBadRequest, "file is required", err)
  54. return
  55. }
  56. defer file.Close()
  57. contentType := header.Header.Get("Content-Type")
  58. validContentTypes := map[string]bool{
  59. "image/jpeg": true, "image/png": true, "image/webp": true, "image/heic": true,
  60. }
  61. if !validContentTypes[contentType] {
  62. writeError(w, http.StatusBadRequest, "unsupported content type", nil)
  63. return
  64. }
  65. ext := ".jpg"
  66. switch contentType {
  67. case "image/png":
  68. ext = ".png"
  69. case "image/webp":
  70. ext = ".webp"
  71. case "image/heic":
  72. ext = ".heic"
  73. }
  74. objectName := "uploads/" + uuid.New().String() + ext
  75. _, err = h.minioClient.PutObject(r.Context(), h.bucket, objectName, file, header.Size,
  76. minio.PutObjectOptions{ContentType: contentType},
  77. )
  78. if err != nil {
  79. writeError(w, http.StatusInternalServerError, "failed to upload file", err)
  80. return
  81. }
  82. fileURL := fmt.Sprintf("%s/%s/%s", h.publicEndpoint, h.bucket, objectName)
  83. writeJSON(w, http.StatusOK, map[string]string{
  84. "file_url": fileURL,
  85. })
  86. }
  87. func (h *UploadHandler) PresignedURL(w http.ResponseWriter, r *http.Request) {
  88. var req presignedURLRequest
  89. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  90. writeError(w, http.StatusBadRequest, "invalid request body", err)
  91. return
  92. }
  93. if req.MaxSizeMB <= 0 || req.MaxSizeMB > 50 {
  94. req.MaxSizeMB = 10
  95. }
  96. validContentTypes := map[string]bool{
  97. "image/jpeg": true, "image/png": true, "image/webp": true, "image/heic": true,
  98. }
  99. if !validContentTypes[req.ContentType] {
  100. writeError(w, http.StatusBadRequest, "unsupported content type", nil)
  101. return
  102. }
  103. fileID := uuid.New().String()
  104. ext := ".jpg"
  105. switch req.ContentType {
  106. case "image/png":
  107. ext = ".png"
  108. case "image/webp":
  109. ext = ".webp"
  110. case "image/heic":
  111. ext = ".heic"
  112. }
  113. objectName := "uploads/" + fileID + ext
  114. policy := minio.NewPostPolicy()
  115. policy.SetBucket(h.bucket)
  116. policy.SetKey(objectName)
  117. policy.SetExpires(time.Now().Add(15 * time.Minute))
  118. policy.SetContentType(req.ContentType)
  119. policy.SetContentLengthRange(1, int64(req.MaxSizeMB)*1024*1024)
  120. uploadURL, formData, err := h.minioClient.PresignedPostPolicy(r.Context(), policy)
  121. if err != nil {
  122. writeError(w, http.StatusInternalServerError, "failed to generate upload URL", err)
  123. return
  124. }
  125. // Replace internal endpoint (minio:9000) with public endpoint for browser uploads
  126. publicUploadURL := uploadURL
  127. uploadURLStr := h.publicEndpoint + uploadURL.Path + "?" + uploadURL.RawQuery
  128. if parsed, err := url.Parse(uploadURLStr); err == nil {
  129. publicUploadURL = parsed
  130. }
  131. fileURL := h.publicEndpoint + "/" + h.bucket + "/" + objectName
  132. writeJSON(w, http.StatusOK, presignedURLResponse{
  133. UploadURL: publicUploadURL.String(),
  134. FileURL: fileURL,
  135. Fields: formData,
  136. })
  137. }