golang vendor path cannot find package

minghua picture minghua · Sep 20, 2018 · Viewed 9.2k times · Source

I'm building the example program from github.com/tarm/serial.

Case 1: It builds ok if the above repo is checked out into $GOPATH/src/github.com/tarm/serial.

Case 2: If the repo is moved under $GOPATH/src/vendor/github.com/tarm/serial the go build command would complain cannot find package "github.com/tarm/serial.

Case 3: The other SO answers suggested to place it under ./vendor so that the package is at ./vendor/github.com/tarm/serial. That does not work either.

The go version is 1.10.4. I believe seeing pages that suggested case 2 or case 3 should work at different times in the past. Has something changed? Do you need to enable the vendor feature somehow?

Details:

The failed command

gotester:~/testdir$ go build uarttest_main.go
uarttest_main.go:5:9: cannot find package "github.com/tarm/serial" in any of:
    /home/gotester/bin/go/src/github.com/tarm/serial (from $GOROOT)
    /home/gotester/testdir/libs/src/github.com/tarm/serial (from $GOPATH)

The source code at ./:

gotester:~/testdir$ cat uarttest_main.go
package main

import (
        "log"
        "github.com/tarm/serial"
)

func main() {
        c := &serial.Config{Name: "COM45", Baud: 115200}
        s, err := serial.OpenPort(c)
        if err != nil {
                log.Fatal(err)
        }

        n, err := s.Write([]byte("test"))
        if err != nil {
                log.Fatal(err)
        }

        buf := make([]byte, 128)
        n, err = s.Read(buf)
        if err != nil {
                log.Fatal(err)
        }
        log.Printf("%q", buf[:n])
}

The ./vendor directory:

gotester:~/testdir$ tree --charset=ascii ./vendor
./vendor
`-- github.com
    `-- tarm
        `-- serial
            |-- basic_test.go
            |-- LICENSE
            |-- README.md
            |-- serial.go
            |-- serial_linux.go
            |-- serial_posix.go
            `-- serial_windows.go

3 directories, 7 files

If run this command now: mv ./vendor/github.com ./libs/src, the build will succeed.

Answer

Adrian picture Adrian · Sep 21, 2018

The Go toolchain expects your projects to be rooted in GOPATH/src. If testdir is your project's root, it needs to be at GOPATH/src/testdir, not at ~/testdir. Then, if you have your dependencies checked out into GOPATH/src/testdir/vendor, you'll get the behavior you're looking for. See Getting started.