我正在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",
},
}
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)
})
如果您想告诉浏览器将响应显示为要下载的文件,可以使用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)
})