自动导入第3方去包

I am a newbie to GO lang and was wondering if there is a way to automatically download all the imports. So let's assume I need to use github.com/gorilla/mux and several other packages in my code base. Should I manually go to my ~/go/src and run go get repo or is there a smarter way of doing dependency management. I am using Goland IDE for my development. Any help is appreciated.

if there is a way to automatically download all the imports

You can download all imported pkgs and their dependencies by running go get from the command line.

I am using Goland IDE for my development

I'm using Goland too. When imports can't be found (ie the import path is highlighted in red), you can place your typing caret over it and press alt + enter and select go get ... from the popup window to automatically import.

You can use dep package manager which will go through your code and automatically import all the packages you use in you code. If you are working with >go1.11 I would suggest to use newly added go mod.

There are several approaces:

  • Simply go get github.com/gorilla/mux which will download sources in your $GOPATH and will be resolved automatically when compiling
  • Use dependency management (godep, glide[deprecated])
  • Use modules (experimental feature in Go 1.11 - Module. Check more here)

If you want a good and stable solution, use dep (.First you have to install it, then run:

cd $GOPATH/src/path/to/project
dep init
dep ensure -add github.com/gorilla/mux

You will see a new folder vendor in your project and 2 new dependency configuration files Gopkg.lock and Gopkg.toml. Read more about godep here.

Then run your main file as usual.