本来是很简单的代码,如下图
package main
import (
"encoding/csv"
"fmt"
"net/http"
)
func getCsvFile(w http.ResponseWriter, r *http.Request) {
var (
csvHeader = []string{"name", "age", "gender"}
records = [][]string{
{"X", "10", "M"},
{"Y", "11", "M"},
{"Z", "12", "M"},
}
)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s.csv", "result"))
w.Header().Set("Content-Transfer-Encoding", "binary")
w.Header().Set("Expires", "0")
w.WriteHeader(http.StatusOK)
f := csv.NewWriter(w)
_ = f.Write(csvHeader)
_ = f.WriteAll(records)
f.Flush()
}
func main() {
http.HandleFunc("/api/csv/download", getCsvFile)
_ = http.ListenAndServe(":11111", nil)
}
在浏览器输入 127.0.0.1:11111/api/csv/download
,就会下载一份 result.csv
文件。
坑
原本很简单的代码踩坑
把 w.WriteHeader(http.StatusOK)
放到 w.Header().Set()
之前就会失败,直接显示 response
的内容。WHY...没看源码,唔知道