Skip to content

Instantly share code, notes, and snippets.

@16892434
Forked from mchirico/gzipWriter.go
Created October 14, 2022 08: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 16892434/a1e4ea64812b50492277130964fac20d to your computer and use it in GitHub Desktop.
Save 16892434/a1e4ea64812b50492277130964fac20d to your computer and use it in GitHub Desktop.
Example of writing a gzip file in go (golang). This appends data to the same file every time it is run. It is important to Flush() the data before closing the file.
/*
This is an example of a golang gzip writer program,
which appends data to a file.
*/
package main
import (
"bufio"
"compress/gzip"
"log"
// "fmt"
"os"
)
type F struct {
f *os.File
gf *gzip.Writer
fw *bufio.Writer
}
func CreateGZ(s string) (f F) {
fi, err := os.OpenFile(s, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
if err != nil {
log.Printf("Error in Create\n")
panic(err)
}
gf := gzip.NewWriter(fi)
fw := bufio.NewWriter(gf)
f = F{fi, gf, fw}
return
}
func WriteGZ(f F, s string) {
(f.fw).WriteString(s)
}
func CloseGZ(f F) {
f.fw.Flush()
// Close the gzip first.
f.gf.Close()
f.f.Close()
}
func main() {
f := CreateGZ("Append.gz")
WriteGZ(f, "gzipWriter.go created this file.\n")
CloseGZ(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment