How to Create a Zip File in Golang

To createzip file in Go, you can use the “os.Create()” method along with the “zip.NewWriter()” function from the zip package.

A zip file is a “compressed archive that contains one or more files”. The zip package allows you to create, and add to existing zip files, extract files from zip files, and more.

To use the zip package, import “archive/zip” into your program.

import "archive/zip"

Once you import the zip package, use its functions to create and read zip files.

Syntax

func Create(name string) (*File, error)

func NewWriter(w io.Writer) *Writer

Example

package main

import (
  "archive/zip"
  "log"
  "os"
)

func main() {
  file, err := os.Create("../new_zip_file.zip")
  if err != nil {
    log.Fatal(err)
  }
  defer file.Close()

  // Create a new zip writer
  wr := zip.NewWriter(file)
  defer wr.Close()

  // Add a file to the zip file
  f, err := wr.Create("app.txt")
  if err != nil {
    log.Fatal(err)
  }

  // Write data to the file
  _, err = f.Write([]byte("Hello Golang"))
  if err != nil {
    log.Fatal(err)
  }
}

In this example, we created a new file called new_zip_file.zip using the os.Create() function.

To create a new zip writer, use the “zip.NewWriter()” function. The NewWriter() function accepts a file name as its argument and returns a Writer type used to write data to the zip file.

In short, we are creating a zip file of app.txt with the content “Hello Golang”.

That’s it!