Passing an CSVExport function to a handler Gin

Issue

I have created a CSV export function for my to-do list application. The function is working, the handler is returning a written file but I get a strange panic in the console from the Gin framework:

http: wrote more than the declared Content-Length

Is that something crucial and how can I fix this panic.

This is my function:

func (r *Repository) CSVExport() (*os.File, error) {
    tasks, err := r.getAllTasks()
    if err != nil {
        return nil, err
    }

    file, err := os.Create("tasks.csv")
    if err != nil {
        return nil, err
    }
    defer file.Close()

    writer := csv.NewWriter(file)
    defer writer.Flush()

    var taskNameList []string
    for _, task := range tasks {
        taskNameList = append(taskNameList, task.Text)
    }

    err = writer.Write(taskNameList)
    if err != nil {
        return nil, err
    }

    return file, nil
}

And this is the handler:

func CSVExport(data model.ListOperations) gin.HandlerFunc {
    return func(c *gin.Context) {
        tasks, err := data.CSVExport()
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Task"})
        }
        c.FileAttachment("./tasks.csv", "tasks.csv")
        c.Writer.Header().Set("attachment", "filename=tasks.csv")
        c.JSON(200, tasks)
    }
}

Solution

Your code has some error:

  • You need to return on error
  • You can’t return JSON after returning your file with fileAttachment (already do this stuff)
func CSVExport(data model.ListOperations) gin.HandlerFunc {
    return func(c *gin.Context) {
        tasks, err := data.CSVExport()
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Task"})
            return //stop it on error
        }
        c.FileAttachment("./tasks.csv", "tasks.csv")
        c.Writer.Header().Set("attachment", "filename=tasks.csv")
        //c.JSON(200, tasks) not need the fileAttachement func do it
    }
}

Answered By – MoiioM

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.