How can I use the “compress/gzip” package to gzip a file?

前端 未结 5 1235
长情又很酷
长情又很酷 2020-12-13 18:48

I\'m new to Go, and can\'t figure out how to use the compress/gzip package to my advantage. Basically, I just want to write something to a file, gzip it and rea

5条回答
  •  时光取名叫无心
    2020-12-13 19:06

    Pretty much the same answer as Laurent, but with the file io:

    import (
      "bytes"
      "compress/gzip"
      "io/ioutil"
    )
    // ...
    var b bytes.Buffer
    w := gzip.NewWriter(&b)
    w.Write([]byte("hello, world\n"))
    w.Close() // You must close this first to flush the bytes to the buffer.
    err := ioutil.WriteFile("hello_world.txt.gz", b.Bytes(), 0666)
    

提交回复
热议问题