Skip to content

Instantly share code, notes, and snippets.

@pwener
Last active March 16, 2021 21:06
Show Gist options
  • Select an option

  • Save pwener/37578f7e416e1441dab3878f5c0e6839 to your computer and use it in GitHub Desktop.

Select an option

Save pwener/37578f7e416e1441dab3878f5c0e6839 to your computer and use it in GitHub Desktop.
Compress file content and save in another file
package main
import (
"bytes"
"encoding/binary"
"io"
"io/ioutil"
"log"
"os"
"github.com/pierrec/lz4"
)
func dump(data []byte, filename string) {
f, err := os.Create(filename)
if err != nil {
log.Fatal("Couldn't open file")
}
defer f.Close()
err = binary.Write(f, binary.LittleEndian, data)
if err != nil {
log.Fatal("Write failed")
}
}
func compress(data []byte) {
// Compress and uncompress an input string.
// s := "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
r := bytes.NewReader(data)
w := &bytes.Buffer{}
zw := lz4.NewWriter(w)
io.Copy(zw, r)
// Closing is *very* important
if err := zw.Close(); err != nil {
return
}
dump(w.Bytes(), "payload.bin")
}
func decompress(data []byte) error {
r := bytes.NewReader(data)
w := &bytes.Buffer{}
zr := lz4.NewReader(r)
if _, err := io.Copy(w, zr); err != nil {
return err
}
dump(w.Bytes(), "decompressed.json")
return nil
}
func main() {
// read our opened jsonFile as a byte array.
byteValue, _ := ioutil.ReadFile("./payload.json")
compress(byteValue)
compressedFileValue, _ := ioutil.ReadFile("./payload.bin")
decompress(compressedFileValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment