Created
June 24, 2015 10:14
-
-
Save xyproto/f4915d7e208771f3adc4 to your computer and use it in GitHub Desktop.
gzip compression/decompression example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"compress/gzip" | |
"io" | |
"io/ioutil" | |
"bytes" | |
"log" | |
) | |
// Write gzipped data to a Writer | |
func gzipWrite(w io.Writer, data []byte) error { | |
// Write gzipped data to the client | |
gw, err := gzip.NewWriterLevel(w, gzip.BestSpeed) | |
defer gw.Close() | |
gw.Write(data) | |
return err | |
} | |
// Write gunzipped data to a Writer | |
func gunzipWrite(w io.Writer, data []byte) error { | |
// Write gzipped data to the client | |
gr, err := gzip.NewReader(bytes.NewBuffer(data)) | |
defer gr.Close() | |
data, err = ioutil.ReadAll(gr) | |
if err != nil { | |
return err | |
} | |
w.Write(data) | |
return nil | |
} | |
func main() { | |
s := "some data" | |
fmt.Println("original:\t", s) | |
var buf bytes.Buffer | |
err := gzipWrite(&buf, []byte(s)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("compressed:\t", buf.String()) | |
var buf2 bytes.Buffer | |
err = gunzipWrite(&buf2, buf.Bytes()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("decompressed:\t", buf2.String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, just use
io.CopyN
instead ofio.Copy
.