我想使用客戶提供的資料為他們提供下載的檔案(例如.txt),而不在我的服務器上創建或持久化任何檔案。我怎樣才能做到呢?
例如,我想用Gin框架從下面的代碼中省略os.Create() defer f.Close()部分:
func serveFile(c *gin.Context){
path := "/tmp/hello.txt"/span>
f, _ := os.Create(path)
defer f.Close()
f.WriteString("hello world")
f.Sync()
/ /span> ...
c.File(path)
}
uj5u.com熱心網友回復:
使用c.Data()來寫一個字串到回應:
c.Data(http.StatusOK, "text/plain"/span>, []byte("hello world"/span>)
uj5u.com熱心網友回復:
在設定適當的回應頭之后,例如
w.Header().Set("Content-Disposition", "attachment; filename=hello.txt" /span>)
w.Header().Set("Content-Type"/span>, r.Header.Get("Content-Type"/span>))
你可以
w.Write("hello world")
你也可以使用http.ServeContent
。https://cs.opensource.google/go/go/ /refs/tags/go1.17.1:src/net/http/fs.go;l=192v
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/312412.html
標籤:
