Zip Compression of Downloaded File using Golang

Gists

This is a sample script for creating a downloaded file as a zip file using Golang. The downloaded file is not created to a file as a temporal file. The zip file is directly created. When you use this, please modify url, downloadedFileName and zipFileName.

Sample script:

package main

import (
    "archive/zip"
    "bytes"
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "time"
)

func main() {
    url := "https://localhost/sample.png"
    downloadedFileName := "sample.png"
    zipFileName := "sample.zip"

    res, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v. ", err)
        os.Exit(1)
    }
    defer res.Body.Close()
    buf := new(bytes.Buffer)
    w := zip.NewWriter(buf)
    fh := &zip.FileHeader{
        Name:     downloadedFileName,
        Modified: time.Now(),
        Method:   8,
    }
    f, err := w.CreateHeader(fh)
    if err != nil {
        log.Fatal(err)
    }
    if _, err := f.Write(body); err != nil {
        log.Fatal(err)
    }
    err = w.Close()
    if err != nil {
        log.Fatal(err)
    }
    file, err := os.Create(zipFileName)
    if err != nil {
        log.Fatal(err)
    }
    if _, err = io.Copy(file, buf); err != nil {
        log.Fatal(err)
    }
    file.Close()
    fmt.Println("Done.")
}

Note:

As an important point, when the file is downloaded, os.FileInfo cannot be used. So in this situation, it uses zip.FileHeader. At that time, please remember to set Method. Method is 0 as the default. This means no compression. The sample script uses 8 to Method. This means the DEFLATE method.

Reference:

 Share!