英文:
Create and serve a file in Golang without saving it to the disk
问题
你可以使用gin.Context.Writer
来直接将数据写入响应体,而无需创建或持久化任何文件。以下是修改后的代码示例:
func serveFile(c *gin.Context) {
data := []byte("hello world")
c.Data(http.StatusOK, "text/plain", data)
}
这样,当客户端请求下载文件时,服务器会直接将数据作为文件内容返回给客户端,而无需在服务器上创建或保存文件。
英文:
I want to use the data provided by the client to serve a file for them to download (say .txt) without creating or persisting any files on my server. How can I do it?
For instance, I want to omit the os.Create()
defer f.Close()
part from the following code with Gin
framework:
func serveFile(c *gin.Context) {
path := "/tmp/hello.txt"
f, _ := os.Create(path)
defer f.Close()
f.WriteString("hello world")
f.Sync()
// ...
c.File(path)
}
答案1
得分: 3
在设置适当的响应头之后,例如:
w.Header().Set("Content-Disposition", "attachment; filename=hello.txt")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
你可以使用以下代码:
w.Write([]byte("hello world"))
你也可以使用http.ServeContent
方法。具体的示例代码可以在以下链接中找到:
https://cs.opensource.google/go/go/+/refs/tags/go1.17.1:src/net/http/fs.go;l=192v
英文:
After setting proper response headers eg
w.Header().Set("Content-Disposition", "attachment; filename=hello.txt")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
you can
w.Write("hello world")
you can also use http.ServeContent
https://cs.opensource.google/go/go/+/refs/tags/go1.17.1:src/net/http/fs.go;l=192v
答案2
得分: 1
使用c.Data()将字符串写入响应:
c.Data(http.StatusOK, "text/plain", []byte("hello world"))
英文:
Use c.Data() to write a string to the response:
c.Data(http.StatusOK, "text/plain", []byte("hello world"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论