php小編蘋果為你帶來了使用Gin在HTTP服務器中即時生成zip/7z存檔的簡潔指南。Gin是一個輕量級的Go語言框架,具有高性能和易用性。本文將介紹如何使用Gin處理HTTP請求,并通過調用系統命令和第三方庫來生成zip和7z存檔文件。無論你是初學者還是有經驗的開發者,跟隨本教程,你將能夠輕松實現這一功能,并為你的Web應用程序增添更多的價值。讓我們開始吧!
問題內容
我使用 Gin 創建一個 HTTP 服務器,我想向用戶提供動態生成的 zip 存檔。
理論上,我可以首先在文件系統上生成一個 zip 文件,然后提供它。但這確實是一個糟糕的方法(在開始下載之前等待 5 分鐘)。我想立即開始將其提供給用戶并在生成內容時推送內容。
我找到了 DataFromReader(示例),但在存檔完成之前不知道 ContentLength。
func DownloadEndpoint(c *gin.Context) { ... c.DataFromReader( http.StatusOK, ContentLength, ContentType, Body, map[string]string{ "Content-Disposition": "attachment; filename=\"archive.zip\""), }, ) }
登錄后復制
我怎樣才能做到這一點?
解決方法
使用流方法和archive/zip 您可以動態創建 zip 并將其流式傳輸到服務器。
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() }
登錄后復制
直接使用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() }
登錄后復制