markbates / pkger

Embed static files in Go binaries (replacement for gobuffalo/packr)
MIT License
1.19k stars 60 forks source link

Binary using pkger not working outside of source folder #38

Closed ContiGuy closed 5 years ago

ContiGuy commented 5 years ago

Hi, I ran pkger in a go modules enabled project, built the binary and ran it from the source folder and it worked. When I run this binary from /tmp it fails.

log:

~/p/play-pkger (master|✚2…) $ cat cmd/play-pkger/play-pkger.go 
package main

import (
    "fmt"

    "github.com/markbates/pkger"
)

func main() {
    err := run()
    if err != nil {
        panic(err)
    }
}

func run() error {
    f, err := pkger.Open("/LICENSE")
    if err != nil {
        return err
    }
    defer f.Close()

    info, err := f.Stat()
    if err != nil {
        return err
    }

    fmt.Println("Name: ", info.Name())
    fmt.Println("Size: ", info.Size())
    fmt.Println("Mode: ", info.Mode())
    fmt.Println("ModTime: ", info.ModTime())
    return nil
}
~/p/play-pkger (master|✚2…) $ pkger
~/p/play-pkger (master|✚2…) $ tree
.
├── cmd
│   └── play-pkger
│       └── play-pkger.go
├── go.mod
├── go.sum
├── LICENSE
└── pkged.go

2 directories, 5 files
~/p/p/c/play-pkger (master|✚2…) $ go build -o /tmp/play-pkger
~/p/p/c/play-pkger (master|✚2…) $ /tmp/play-pkger
Name:  LICENSE
Size:  11353
Mode:  -rw-r--r--
ModTime:  2019-11-20 10:46:18.276189286 +0100 CET
~/p/p/c/play-pkger (master|✚2…) $ cd /tmp/
/tmp $ /tmp/play-pkger
2019/11/20 10:51:45 exit status 1: "go list -json -m": go list -m: not using modules

panic: open /LICENSE: no such file or directory

goroutine 1 [running]:
main.main()
    /home/play/pr/play-pkger/cmd/play-pkger/play-pkger.go:12 +0x44
/tmp [2] $ 
ContiGuy commented 5 years ago

It seems that this binary also would not work on a machine which doesn't have go installed.

nlepage commented 5 years ago

I think pkged.go is not built in your binary.

Adding _ "path/to/your/module" in your imports should fix the problem.

ContiGuy commented 5 years ago

@nlepage Thanks for the reply! But unfortunately the import doesn't help.

markbates commented 5 years ago

Use pkger -o cmd/play-pkger to put the pkged.go file in the package you need it.

fnikolai commented 5 years ago

@ContiGuy what if you compile it on the current directory and then move the binary to /tmp ?

Also, what is your version of go ?