Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing a zip file in memory

Tags:

go

I am trying to edit a zip file in memory in Go and return the zipped file through a HTTP response

The goal is to add a few files to a path in the zip file example

I add a log.txt file in my path/to/file route in the zipped folder

All this should be done without saving the file or editing the original file.

like image 557
user4920718 Avatar asked Mar 24 '26 06:03

user4920718


1 Answers

I have implemented a simple version of real-time stream compression, which can correctly compress a single file. If you want it to run efficiently, you need a lot of optimization.

This is only for reference. If you need more information, you should set more useful HTTP header information before compression so that the client can correctly process the response data.

package main

import (
    "archive/zip"
    "io"
    "net/http"
    "os"

    "github.com/gin-gonic/gin"
)

func main() {
    engine := gin.Default()
    engine.GET("/log.zip", func(c *gin.Context) {
        f, err := os.Open("./log.txt")
        if err != nil {
            c.String(http.StatusInternalServerError, err.Error())
            return
        }

        defer f.Close()
        info, err := f.Stat()
        if err != nil {
            c.String(http.StatusInternalServerError, err.Error())
            return
        }

        z := zip.NewWriter(c.Writer)
        head, err := zip.FileInfoHeader(info)
        if err != nil {
            c.String(http.StatusInternalServerError, err.Error())
            return
        }

        defer z.Close()

        w, err := z.CreateHeader(head)
        if err != nil {
            c.String(http.StatusInternalServerError, err.Error())
            return
        }

        _, err = io.Copy(w, f)
        if err != nil {
            c.String(http.StatusInternalServerError, err.Error())
            return
        }
    })

    engine.Run("127.0.0.1:8080")
}

like image 55
Qi Yin Avatar answered Mar 26 '26 10:03

Qi Yin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!