使用Docker API for GO时出现问题-无法导入“ nat”

I am trying to use the docker API for golang that is available from github.com/docker/docker/client. So far I am able to start the containers on the port that is predefined during image built. I am trying to map the port during runtime using the API; something equivalent to

docker run -p 8083:8082 -d myImage:1.0.0

I tried to do something like the following for mapping the ports:

host_config := &container.HostConfig{
     PortBindings: nat.PortMap{
     "8082/tcp": []nat.PortBinding{
         {
             HostIP: "0.0.0.0",
             HostPort: "8983",
         },
      },
   },
}

The problem here is that the variable "nat" lives inside the vendor folder of the API. I couldn't import something directly from the go vendor folder. Someone on the stackoverflow suggested to copy the go-connection folder into the github folder and remove the nested vendor directory. I did as suggested and created a path as follows:

"github.com/docker/go-connections/nat"

now I get the following error during compile time:

src\main\createcontainer1.go:53: cannot use "github.com/docker/go-connections/nat".PortSet literal (type "github.com/docker/go-connections/nat".PortSet) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortSet in field value

src\main\createcontainer1.go:65: cannot use "github.com/docker/go-connections/nat".PortMap literal (type "github.com/docker/go-connections/nat".PortMap) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortMap in field value

Have anyone faced this issue and overcome it? I am using the Go ver 1.8.

So you need to do more than just copy it, you need to move it. The same package located in two different locations are different packages to the go tool (because it can't guarantee they are identical, so it uses fully-qualified import paths).

If a package you're using has a vendor directory, and you need to use the packages in it, you have two options:

  • Move everything out of the vendor directory in that package into your $GOPATH/src
  • Vendor the package itself, and then move everything from the package's vendor directory into your project's vendor directory (<project root>/vendor). This is known as "flattening" your vendored dependencies, and most Go vendoring utilities (ex. Govendor or Godep) can do this, either automatically or with a flag. You can also do it manually, though.

The latter is generally the recommended strategy. The important key, though, is that the package itself cannot have a version of that library in its own vendor directory, as Go tool automatically uses the deepest vendored version of a package that it can access.