如何使用Go语言处理CSV文件?

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

Go how to response csv file?

问题

我正在创建一个Go服务器,并希望用CSV文件作为响应。我写了以下代码,但是它没有导致浏览器下载CSV文件。如何提示浏览器下载CSV文件?

import "github.com/gocarina/gocsv"

type Test struct {
	ID     int
	Name   string
	Delete string
}

router.Get("/test", func(writer http.ResponseWriter, request *http.Request) {
	writer.WriteHeader(http.StatusOK)

	tests := []*Test{
		{
			ID:     1,
			Name:   "a",
			Delete: "delete",
		},
		{
			ID:     2,
			Name:   "b",
			Delete: "delete",
		},
	}

	writer.Header().Set("Content-Disposition", "attachment; filename=file.csv")
	writer.Header().Set("Content-Type", "text/csv")

	err := gocsv.MarshalFile(&tests, writer)
	if err != nil {
		logger.Error("MarshalFile", zap.Error(err))
	}
})

你需要在响应头中设置Content-DispositionContent-Type,以便浏览器能够正确地下载CSV文件。

英文:

I am creating a server in Go and I want to respond with a CSV file.

I wrote the following, this does not cause the browser to download the CSV file. How can I prompt the browser to download the CSV file?

import "github.com/gocarina/gocsv"

type Test struct {
	ID   int
	Name string
	Delete string
}

router.Get("/test", func(writer http.ResponseWriter, request *http.Request) {
    writer.WriteHeader(http.StatusOK)


    tests := []*Test{
        {
			ID:   1,
			Name: "a",
			Delete: "delete",
		},
		{
			ID:   2,
			Name: "b",
			Delete: "delete",
		},
	}

	w := multipart.NewWriter(writer)
	ww, err := w.CreateFormFile("file.csv", "file.csv")
	if err != nil {
		logger.Error("CreateFormfile", zap.Error(err))
	}
	gocsv.Marshal(tests, ww)

})

答案1

得分: 6

如果你想告诉浏览器将响应呈现为可下载的文件,你可以使用Content-Disposition头部:

rw.Header().Add("Content-Disposition", `attachment; filename="test.csv"`)

至于输出CSV文档本身,我不确定你试图通过响应多部分编码来实现什么目标,但你应该直接将CSV文件编组到原始的HTTP响应写入器中:

router.Get("/test", func(rw http.ResponseWriter, req *http.Request) {

        tests := []*Test{
            {
                ID:   1,
                Name: "a",
                Delete: "delete",
            },
            {
                ID:   2,
                Name: "b",
                Delete: "delete",
            },
        }

        gocsv.Marshal(tests, rw)

})
英文:

If you want to tell the browser the to present the response as a file to download, you can use the Content-Disposition header:

rw.Header().Add("Content-Disposition", `attachment; filename="test.csv"`)

As far as outputting the CSV document itself,
I'm not sure what you're trying to achieve by responding with a multipart encoding, but you should just marshal the CSV file directly into the original HTTP response writer:

router.Get("/test", func(rw http.ResponseWriter, req *http.Request) {

        tests := []*Test{
            {
                ID:   1,
                Name: "a",
                Delete: "delete",
            },
            {
                ID:   2,
                Name: "b",
                Delete: "delete",
            },
        }

        gocsv.Marshal(tests, rw)

})

huangapple
  • 本文由 发表于 2021年6月28日 19:34:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/68162651.html
匿名

发表评论

匿名网友

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

确定