How can I open files relative to my GOPATH?

前端 未结 4 784
忘掉有多难
忘掉有多难 2020-12-05 09:36

I\'m using io/ioutil to read a small text file:

fileBytes, err := ioutil.ReadFile(\"/absolute/path/to/file.txt\")

And that wor

4条回答
  •  春和景丽
    2020-12-05 10:03

    I wrote gobundle to solve exactly this problem. It generates Go source code from data files, which you then compile into your binary. You can then access the file data through a VFS-like layer. It's completely portable, supports adding entire file trees, compression, etc.

    The downside is that you need an intermediate step to build the Go files from the source data. I usually use make for this.

    Here's how you'd iterate over all files in a bundle, reading the bytes:

    for _, name := range bundle.Files() {
        r, _ := bundle.Open(name)
        b, _ := ioutil.ReadAll(r)
        fmt.Printf("file %s has length %d\n", name, len(b))
    }
    

    You can see a real example of its use in my GeoIP package. The Makefile generates the code, and geoip.go uses the VFS.

提交回复
热议问题