Created
December 22, 2016 01:16
-
-
Save bussiere/0bab337eb1824a9e09db3d75ab0fed73 to your computer and use it in GitHub Desktop.
compress uncompress a string in golang
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 ( | |
"bytes" | |
"compress/gzip" | |
"fmt" | |
"encoding/base64" | |
"io/ioutil" | |
) | |
func main() { | |
var b bytes.Buffer | |
gz := gzip.NewWriter(&b) | |
if _, err := gz.Write([]byte("YourDataHere")); err != nil { | |
panic(err) | |
} | |
if err := gz.Flush(); err != nil { | |
panic(err) | |
} | |
if err := gz.Close(); err != nil { | |
panic(err) | |
} | |
str := base64.StdEncoding.EncodeToString(b.Bytes()) | |
fmt.Println(str) | |
data, _ := base64.StdEncoding.DecodeString(str) | |
fmt.Println(data) | |
rdata := bytes.NewReader(data) | |
r,_ := gzip.NewReader(rdata) | |
s, _ := ioutil.ReadAll(r) | |
fmt.Println(string(s)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this works for in memory operations of an io.Reader, but not for storing strings to disk, converting the compressed reader to a string results in the original size of the string