php小編蘋(píng)果為你帶來(lái)了使用Gin在HTTP服務(wù)器中即時(shí)生成zip/7z存檔的簡(jiǎn)潔指南。Gin是一個(gè)輕量級(jí)的Go語(yǔ)言框架,具有高性能和易用性。本文將介紹如何使用Gin處理HTTP請(qǐng)求,并通過(guò)調(diào)用系統(tǒng)命令和第三方庫(kù)來(lái)生成zip和7z存檔文件。無(wú)論你是初學(xué)者還是有經(jīng)驗(yàn)的開(kāi)發(fā)者,跟隨本教程,你將能夠輕松實(shí)現(xiàn)這一功能,并為你的Web應(yīng)用程序增添更多的價(jià)值。讓我們開(kāi)始吧!
問(wèn)題內(nèi)容
我使用 Gin 創(chuàng)建一個(gè) HTTP 服務(wù)器,我想向用戶提供動(dòng)態(tài)生成的 zip 存檔。
理論上,我可以首先在文件系統(tǒng)上生成一個(gè) zip 文件,然后提供它。但這確實(shí)是一個(gè)糟糕的方法(在開(kāi)始下載之前等待 5 分鐘)。我想立即開(kāi)始將其提供給用戶并在生成內(nèi)容時(shí)推送內(nèi)容。
我找到了 DataFromReader(示例),但在存檔完成之前不知道 ContentLength。
func DownloadEndpoint(c *gin.Context) {
...
c.DataFromReader(
http.StatusOK,
ContentLength,
ContentType,
Body,
map[string]string{
"Content-Disposition": "attachment; filename=\"archive.zip\""),
},
)
}
登錄后復(fù)制
我怎樣才能做到這一點(diǎn)?
解決方法
使用流方法和archive/zip 您可以動(dòng)態(tài)創(chuàng)建 zip 并將其流式傳輸?shù)椒?wù)器。
package main
import (
"os"
"archive/zip"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.Writer.Header().Set("Content-type", "application/octet-stream")
c.Stream(func(w io.Writer) bool {
// Create a zip archive.
ar := zip.NewWriter(w)
file1, _ := os.Open("filename1")
file2, _ := os.Open("filename2")
c.Writer.Header().Set("Content-Disposition", "attachment; filename='filename.zip'")
f1, _ := ar.Create("filename1")
io.Copy(f1, file1)
f2, _ := ar.Create("filename2")
io.Copy(f2, file2)
ar.Close()
return false
})
})
r.Run()
}
登錄后復(fù)制
直接使用ResponseWriter
package main
import (
"io"
"os"
"archive/zip"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.Writer.Header().Set("Content-type", "application/octet-stream")
c.Writer.Header().Set("Content-Disposition", "attachment; filename='filename.zip'")
ar := zip.NewWriter(c.Writer)
file1, _ := os.Open("filename1")
file2, _ := os.Open("filename2")
f1, _ := ar.Create("filename1")
io.Copy(f1, file1)
f2, _ := ar.Create("filename1")
io.Copy(f1, file2)
ar.Close()
})
r.Run()
}
登錄后復(fù)制






