gobuffalo / packr

The simple and easy way to embed static files into Go binaries.
MIT License
3.41k stars 196 forks source link

packr.File.Read() always returns empty #32

Closed rskumar closed 6 years ago

rskumar commented 6 years ago

While in Walk func, reading content using File.Read() returns empty string.

Code -

box.Walk(func(p string, f packr.File) error {
    var b []byte
    err := f.Read(b)
    // ...
}

b remains always empty. Though content can be read using box.MustByte(...) but then why we have Read function.

markbates commented 6 years ago

The problem is in your code, you need to give the byte slice a size for the bytes to be read from. See the docs for io.Reader, https://golang.org/pkg/io/#Reader.

You could rewrite the code like this:

package main

import (
    "github.com/gobuffalo/packr"
    "github.com/kr/pretty"
)

func main() {
    box := packr.NewBox(".")
    box.Walk(func(p string, f packr.File) error {
        fi, err := f.FileInfo()
        if err != nil {
            return err
        }
        b := make([]byte, fi.Size())
        if _, err := f.Read(b); err != nil {
            return err
        }
        pretty.Println("### b ->", string(b))

        // this also works:
        // _, err := io.Copy(os.Stdout, f)
        // return err
        return nil
    })
}