调整项目结构,factory只负责暴露方法,不实现业务细节
This commit is contained in:
@@ -43,31 +43,29 @@ func NewUploadHandler(cfg UploadHandlerConfig) *UploadHandler {
|
||||
// 表单字段: file (文件)
|
||||
// 可选字段: prefix (对象键前缀,会覆盖配置中的前缀)
|
||||
func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
handler := commonhttp.NewHandler(w, r)
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
handler.Error(4001, "Method not allowed")
|
||||
commonhttp.Error(w, 4001, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
// 解析multipart表单
|
||||
err := r.ParseMultipartForm(h.maxFileSize)
|
||||
if err != nil {
|
||||
handler.Error(4002, fmt.Sprintf("Failed to parse form: %v", err))
|
||||
commonhttp.Error(w, 4002, fmt.Sprintf("Failed to parse form: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// 获取文件
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
handler.Error(4003, fmt.Sprintf("Failed to get file: %v", err))
|
||||
commonhttp.Error(w, 4003, fmt.Sprintf("Failed to get file: %v", err))
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 检查文件大小
|
||||
if h.maxFileSize > 0 && header.Size > h.maxFileSize {
|
||||
handler.Error(1001, fmt.Sprintf("File size exceeds limit: %d bytes", h.maxFileSize))
|
||||
commonhttp.Error(w, 1001, fmt.Sprintf("File size exceeds limit: %d bytes", h.maxFileSize))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -82,7 +80,7 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
handler.Error(1002, fmt.Sprintf("File extension not allowed. Allowed: %v", h.allowedExts))
|
||||
commonhttp.Error(w, 1002, fmt.Sprintf("File extension not allowed. Allowed: %v", h.allowedExts))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -110,14 +108,14 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
err = h.storage.Upload(ctx, objectKey, file, contentType)
|
||||
if err != nil {
|
||||
handler.SystemError(fmt.Sprintf("Failed to upload file: %v", err))
|
||||
commonhttp.SystemError(w, fmt.Sprintf("Failed to upload file: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// 获取文件URL
|
||||
fileURL, err := h.storage.GetURL(objectKey, 0)
|
||||
if err != nil {
|
||||
handler.SystemError(fmt.Sprintf("Failed to get file URL: %v", err))
|
||||
commonhttp.SystemError(w, fmt.Sprintf("Failed to get file URL: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -130,7 +128,7 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
UploadTime: time.Now(),
|
||||
}
|
||||
|
||||
handler.SuccessWithMessage("Upload successful", result)
|
||||
commonhttp.Success(w, result, "Upload successful")
|
||||
}
|
||||
|
||||
// generateUniqueFilename 生成唯一文件名
|
||||
|
||||
Reference in New Issue
Block a user