将CSVExport函数传递给Gin的处理程序。

huangapple go评论85阅读模式
英文:

Passing an CSVExport function to a handler Gin

问题

我已经为我的待办事项应用程序创建了一个CSV导出功能。该功能正常工作,处理程序返回了一个已写入的文件,但是我在Gin框架的控制台中收到了一个奇怪的恐慌信息:

> http: wrote more than the declared Content-Length

这是一些关键的东西吗?我该如何解决这个恐慌。

这是我的函数:

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
}

这是处理程序:

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)
	}
}
英文:

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)
	}
}

答案1

得分: 1

你的代码有一些错误:

  • 在错误的情况下,你需要返回。
  • 在使用fileAttachment返回文件后,不能再返回JSON(fileAttachment已经完成了这个操作)。
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": "无效的任务"})
            return // 在错误的情况下返回
        }
        c.FileAttachment("./tasks.csv", "tasks.csv")
        c.Writer.Header().Set("attachment", "filename=tasks.csv")
        // 不需要使用fileAttachment函数后再返回JSON
    }
}
英文:

Your code has some error:

  • You need to return on error
  • You can't return JSON after returning your file with fileAttachment (it already does 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
    }
}

huangapple
  • 本文由 发表于 2022年5月20日 18:48:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/72317656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定