Golang: convert to JSON.GZ and write to file

Trying the following output with my data:

  • Convert to JSON string and write to file: output.json (this part works)
  • Gzip Compress JSON string and write to json.gz file: output.json.gz ( DOES NOT WORK )

The code works fine and writes to both files. But the gzipped file gives this error when I try to unzip it:Data error in 'output.json'. File is broken

Here's the code:

package main

import (
    "bytes"
    "compress/gzip"
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type Generic struct {
    Name string
    Cool bool
    Rank int
}

func main() {
    generic := Generic{"Golang", true, 100}
    fileJson, _ := json.Marshal(generic)
    err := ioutil.WriteFile("output.json", fileJson, 0644)
    if err != nil {
        fmt.Printf("WriteFileJson ERROR: %+v", err)
    }

    var fileGZ bytes.Buffer
    zipper := gzip.NewWriter(&fileGZ)
    defer zipper.Close()
    _, err = zipper.Write([]byte(string(fileJson)))
    if err != nil {
        fmt.Printf("zipper.Write ERROR: %+v", err)
    }
    err = ioutil.WriteFile("output.json.gz", []byte(fileGZ.String()), 0644)
    if err != nil {
        fmt.Printf("WriteFileGZ ERROR: %+v", err)
    }
}

      

What did I miss?

+3


source to share


1 answer


You need to call zipper.Close () right after you finish writing

http://play.golang.org/p/xNeMg3aXxO



_, err = zipper.Write(fileJson)
if err != nil {
    log.Fatalf("zipper.Write ERROR: %+v", err)
}
err := zipper.Close() // call it explicitly and check error 

      

The call defer zipper.Close()

will trigger the call at the end of the main function. Until you name it .Close()

, the data is written to an intermediate buffer and is not flushed back to the actual file.

+7


source







All Articles