Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created October 23, 2018 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/0d91da9888393e6ee737a67c57eeab70 to your computer and use it in GitHub Desktop.
Save tanaikech/0d91da9888393e6ee737a67c57eeab70 to your computer and use it in GitHub Desktop.
Zip Compression of Downloaded File using Golang

Zip Compression of Downloaded File using Golang

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment