<p>Hi all,</p>
<p>I've built a small webserver which produces some statistics for me. What I'd like to do is provide a link to download that data as a csv file bit not sure how to do it.</p>
<p>Do I need to generate a temporary file on my system, then redirect user to it and then delete it afterwards? Or is there a clever way I'm missing of using an io.writer to directly send the file to the user?</p>
<p>I don't anticipate the files being very big but don't want them hanging round on my system.</p>
<p>Thanks for any help.</p>
<hr/>**评论:**<br/><br/>captncraig: <pre><pre><code>func ServeCSV(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type","text/csv")
w.Write(myGeneratedCsv)
}
</code></pre>
<p>No need to hit the disk.</p></pre>acharlton: <pre><p>Perfect, thank you - new to web development and think there are a few things like this I just don't know yet!</p></pre>allhatenocattle: <pre><p>If you want to set a filename hint, you can also add:</p>
<pre><code>w.Header().Set("Content-Disposition", `inline; filename="myfile.csv"`)
</code></pre></pre>acharlton: <pre><p>Thank you - answered my next question before I even asked it!</p></pre>acharlton: <pre><p>Thank you both so much captncraig & allhatenocattle, that worked beautifully. </p>
<p>Just in case anyone was interested, I tried a quick proof of concept to serve an xlsx file instead and it worked a treat.</p>
<pre><code>package main
import (
"fmt"
"io"
"net/http"
"github.com/tealeg/xlsx"
)
func main() {
http.HandleFunc("/test/", serveSheet)
http.ListenAndServe(":8080", nil)
}
func serveSheet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
w.Header().Set("Content-Disposition", `inline; filename="test.xlsx"`)
spreadsheet(w)
}
func spreadsheet(w io.Writer) {
var file *xlsx.File
var sheet *xlsx.Sheet
var row *xlsx.Row
var cell *xlsx.Cell
var err error
file = xlsx.NewFile()
sheet, err = file.AddSheet("Sheet1")
if err != nil {
fmt.Println(err)
}
row = sheet.AddRow()
cell = row.AddCell()
cell.Value = "I am a cell!"
err = file.Write(w)
if err != nil {
fmt.Printf(err.Error())
}
}
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传