Files
gochat/internal/handler/api/v1/upload_handler.go
T
2026-06-04 15:44:48 +08:00

93 lines
2.6 KiB
Go

package v1
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/service"
"github.com/gochat/gochat/pkg/response"
)
// UploadHandler handles file upload endpoints (account-level + widget direct + account direct).
type UploadHandler struct {
svc *service.UploadService
}
// NewUploadHandler creates a new UploadHandler.
func NewUploadHandler(svc *service.UploadService) *UploadHandler {
return &UploadHandler{svc: svc}
}
// Upload handles POST /api/v1/accounts/:id/upload — account-level file upload.
// Reference: Chatwoot api/v1/accounts/:account_id/upload
func (h *UploadHandler) Upload(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "account_id is required")
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "file is required")
return
}
result, svcErr := h.svc.AccountUpload(c.Request.Context(), accountID, service.AccountUploadRequest{
FileHeader: fileHeader,
})
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, result)
}
// DirectUpload handles POST /api/v1/widget/direct_uploads — widget direct file upload.
// Reference: Chatwoot POST /widget/direct_uploads
func (h *UploadHandler) DirectUpload(c *gin.Context) {
fileHeader, err := c.FormFile("file")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "file is required")
return
}
result, svcErr := h.svc.WidgetDirectUpload(c.Request.Context(), service.WidgetDirectUploadRequest{
FileHeader: fileHeader,
})
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, result)
}
// AccountDirectUpload handles POST /api/v1/accounts/:id/direct_uploads — account-level staged upload.
// Returns a blob/UUID for later attachment to messages.
// Reference: Chatwoot POST /api/v1/accounts/:account_id/direct_uploads
func (h *UploadHandler) AccountDirectUpload(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "account_id is required")
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "file is required")
return
}
result, svcErr := h.svc.AccountDirectUpload(c.Request.Context(), accountID, service.AccountDirectUploadRequest{
FileHeader: fileHeader,
})
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, result)
}