去如何响应csv文件?
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",
},
}
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
header:
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)
})
我正在用 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
header:
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)
})