From 3b6fa12911c90fb5d4da30523c9a530512d3c261 Mon Sep 17 00:00:00 2001 From: Jose Antonio Cely Saidiza Date: Wed, 5 Mar 2025 15:12:11 -0500 Subject: [PATCH] change panic by err --- context.go | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/context.go b/context.go index 7020e84..c603030 100644 --- a/context.go +++ b/context.go @@ -121,34 +121,43 @@ func (c *Context) GetQueueClient() *asynq.Client { return client } -func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { +func (c *Context) GetUploadedFile(name string) (*UploadedFileInfo, error) { file, fileHeader, err := c.Request.httpRequest.FormFile(name) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error retrieving file: %v", err) } defer file.Close() + + // Extract the file extension ext := strings.TrimPrefix(path.Ext(fileHeader.Filename), ".") tmpFilePath := filepath.Join(os.TempDir(), fileHeader.Filename) tmpFile, err := os.Create(tmpFilePath) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error creating temporary file: %v", err) } + defer tmpFile.Close() + // Copy the uploaded file content to the temporary file buff := make([]byte, 100) for { n, err := file.Read(buff) if err != nil && err != io.EOF { - panic("error with uploaded file") + return nil, fmt.Errorf("error reading uploaded file: %v", err) } if n == 0 { break } - n, _ = tmpFile.Write(buff[:n]) + _, err = tmpFile.Write(buff[:n]) + if err != nil { + return nil, fmt.Errorf("error writing to temporary file: %v", err) + } } + + // Get file info for the temporary file tmpFileInfo, err := os.Stat(tmpFilePath) if err != nil { - panic(fmt.Sprintf("error with file,[%v]", err.Error())) + return nil, fmt.Errorf("error getting file info: %v", err) } - defer tmpFile.Close() + uploadedFileInfo := &UploadedFileInfo{ FullPath: tmpFilePath, Name: fileHeader.Filename, @@ -156,7 +165,7 @@ func (c *Context) GetUploadedFile(name string) *UploadedFileInfo { Extension: ext, Size: int(tmpFileInfo.Size()), } - return uploadedFileInfo + return uploadedFileInfo, nil } func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error { @@ -185,7 +194,7 @@ func (c *Context) MoveFile(sourceFilePath string, destFolderPath string) error { for { n, err := srcFile.Read(buff) if err != nil && err != io.EOF { - panic(fmt.Sprintf("error moving file %v", sourceFilePath)) + return fmt.Errorf("error moving file: %v", sourceFilePath) } if n == 0 { break @@ -229,7 +238,7 @@ func (c *Context) CopyFile(sourceFilePath string, destFolderPath string) error { for { n, err := srcFile.Read(buff) if err != nil && err != io.EOF { - panic(fmt.Sprintf("error moving file %v", sourceFilePath)) + return fmt.Errorf("error moving file: %v", sourceFilePath) } if n == 0 { break