Created
April 12, 2016 13:16
-
-
Save dougneal/8fdc86516a76b69a51aa33fcadc4fdd1 to your computer and use it in GitHub Desktop.
Marshalling binary data to JSON results in corruption
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" | |
"encoding/json" | |
"io/ioutil" | |
) | |
const ec2_userdata string = `#cloud-config | |
bootcmd: | |
- echo "hello world" | |
` | |
func check(e error) { | |
if e != nil { | |
panic(e) | |
} | |
} | |
func main() { | |
var buffer bytes.Buffer | |
gzipWriter := gzip.NewWriter(&buffer) | |
gzipWriter.Write([]byte(ec2_userdata)) | |
gzipWriter.Close() | |
mapD := map[string]string{"gzip": buffer.String()} | |
mapB, _ := json.Marshal(mapD) | |
var err error | |
var raw []byte | |
err = ioutil.WriteFile("output.json", mapB, 0644) | |
check(err) | |
raw, err = ioutil.ReadFile("output.json") | |
check(err) | |
var unmarshalled map[string]interface{} | |
err = json.Unmarshal([]byte(raw), &unmarshalled) | |
check(err) | |
gzip_in := unmarshalled["gzip"].(string) | |
err = ioutil.WriteFile("unmarshalled.gz", []byte(gzip_in), 0644) | |
check(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try to gunzip the resulting unmarshalled.gz file, it won't work.