New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read doesn't write to slice. #62

Closed
kinghunter58 opened this Issue Dec 1, 2018 · 2 comments

Comments

Projects
None yet
2 participants
@kinghunter58

kinghunter58 commented Dec 1, 2018

I generated the file assets_vfsdata.go and everything is ok, but I need to read a file and compress it to base64. When executing the code below I get an empty slice. Could not figure why.

f, err := assets.Open("index.html")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sl := []byte{}
n, err := f.Read(sl)
fmt.Println(n, err)
fmt.Println(sl)

After some debugging I found out that f.gr.Read(p) in the read method of vfsgen۰CompressedFile doesn't change the value of the slice. Maybe the bug is there?

@dmitshur

This comment has been minimized.

Member

dmitshur commented Dec 2, 2018

Hi @kinghunter58,

It looks like there might be a bug in your code to read from f.

The io.Reader interface documentation notes:

Read reads up to len(p) bytes into p.

In the code you posted, I see:

sl := []byte{}
n, err := f.Read(sl)

The length of slice sl is 0, so f.Read can only read zero bytes. You should give it a byte slice of non-zero length for it to be able to read more.

Alternatively, you can use a higher-level utility like ioutil.ReadAll to read all bytes from f with one function call:

b, err := ioutil.ReadAll(f)
if err != nil {
    // Handle error.
}
// Use b...

Or use io.Copy into bytes.Buffer:

var buf bytes.Buffer
_, err := io.Copy(&buf, f)
if err != nil {
    // Handle error.
}
// Use buf...

You mentioned you wanted to encode the file into base64. You could do that with something like:

encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
_, err := io.Copy(encoder, f)
if err != nil {
    // Handle error.
}
err = encoder.Close()
if err != nil {
    // Handle error.
}

@dmitshur dmitshur added the question label Dec 2, 2018

@kinghunter58

This comment has been minimized.

kinghunter58 commented Dec 2, 2018

Thank you very much @dmitshur,
using ioutil.ReadAll resolved my issue. The problem was that my slice, as you said, had a length of 0. Thank you again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment