Reputation: 792
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:
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
.
Upvotes: 6
Views: 3375
Reputation: 34272
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))
Upvotes: 7