Web server with dynamic downloads?

polaris · · 525 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi all,</p> <p>I&#39;ve built a small webserver which produces some statistics for me. What I&#39;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&#39;m missing of using an io.writer to directly send the file to the user?</p> <p>I don&#39;t anticipate the files being very big but don&#39;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(&#34;Content-Type&#34;,&#34;text/csv&#34;) 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&#39;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(&#34;Content-Disposition&#34;, `inline; filename=&#34;myfile.csv&#34;`) </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 &amp; 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 ( &#34;fmt&#34; &#34;io&#34; &#34;net/http&#34; &#34;github.com/tealeg/xlsx&#34; ) func main() { http.HandleFunc(&#34;/test/&#34;, serveSheet) http.ListenAndServe(&#34;:8080&#34;, nil) } func serveSheet(w http.ResponseWriter, r *http.Request) { w.Header().Set(&#34;Content-Type&#34;, &#34;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#34;) w.Header().Set(&#34;Content-Disposition&#34;, `inline; filename=&#34;test.xlsx&#34;`) 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(&#34;Sheet1&#34;) if err != nil { fmt.Println(err) } row = sheet.AddRow() cell = row.AddCell() cell.Value = &#34;I am a cell!&#34; err = file.Write(w) if err != nil { fmt.Printf(err.Error()) } } </code></pre></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

525 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传