6

I'm rather new to Golang and not sure yet, how to use certain language constructs. Currently I have following code (with test debug outputs), which does not provide expected result:

    json, _ := json.Marshal(struct)
    fmt.Println(json)

    f,_ := os.Create(fmt.Sprintf("/tmp/%s.json", "asd"))

    i,_ := f.Write(json)
    fmt.Println(i)  

    b, err := ioutil.ReadAll(f)
    fmt.Print(b)

I expect the following behaviour:

  • translating the struct to a byte array
  • creating a new file
  • append the byte array to the file

However, the file is always empty when I run the code in my environment (AWS Lambda), as well as using it in the Golang Playground. The output of above code looks like this:

[123 34 ... <hug array of bytes>]
1384
[]

which leads me to believe I'm using f.Write() not correctly, although I followed the package documentation. All other outputs indicate expected behavior, so what is my mistake? I'm somewhat restricted to using the File interface, otherwise I'd have gone with ioutil.WriteFile(). My assumption is a misunderstanding of pointer/values at some point, but the compiler prevented a usage of &f.

1 Answer 1

7

After f.Write(), your current position in the file is at the end of it, so ioutil.ReadAll() will read from that position and return nothing.

You need to call f.Sync() to make sure that the data is persistently saved to the disk, and then f.Seek(0, 0) to rewind to the beginning of the file first.

Update: from comments, it seems that you only need to serialize the JSON and pass it forward as io.Reader, for that you don't really need a file, thanks to bytes.Buffer:

data, _ := json.Marshal(s)
buf := bytes.NewBuffer(data)
b, _ := ioutil.ReadAll(buf)
fmt.Print(string(b))
5
  • might be useful to explain what sync and seek do. May 27, 2020 at 10:22
  • Oh wow, I would not have expected those action to be necessary. Thanks a lot, it works in both environments now! So if I do not actually save the file on disk and just pass the File object to another function, I can probably omit the Sync() and just 'rewind' the position counter.
    – kopaka
    May 27, 2020 at 10:29
  • @kopaka I am actually not quite sure how exactly it might behave without Sync() and whether that's platform-specific, need to check the fsync / fseek docs.
    – bereal
    May 27, 2020 at 10:43
  • @bereal and for anyone wondering: it does in fact work, since I'm passing the File object to another function, which stores it to an S3 bucket, so there is no need ever to actually physically store the file.
    – kopaka
    May 27, 2020 at 13:16
  • 1
    @kopaka in that case you don't really need a file, check bytes.Buffer.
    – bereal
    May 27, 2020 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.