Old Style: GOPATH
Project item in GO
GOPATH
is a kind of environment variable, that means the path of GO project;GOPATH
is recommended as only one in one system;src, pkg, bin
is recommend as the subdirectory asGOPATH
;src
: store the source code of GO project; When we use version control tools likegit , svn etc
,what only need is control the file inGOPATH\src
directory;pkg
: store the cache file;bin
: store the executable file;
GO project structure
Personal
In go language, package is the unit of caller. While different developer may meet with naming conflict, if they both develop someName
package with the same go structure. Using github
info is recommend as personal go structure, like :
This way we could get others package with confidence, for example:
1 | go get gihub.com/GuardingDog/GoLearning |
company
New Fashion: Modules
Go 1.11 introduced Modules. This approach is the default build mode since Go 1.16, therefore the use of GOPATH
is not recommended.
Modules aim to solve problems related to dependency management, version selection and reproducible builds; they also enable users to run Go code outside of GOPATH
.
Using Modules is pretty straightforward. Select any directory outside GOPATH
as the root of your project, and create a new module with the go mod init
command.
A go.mod
file will be generated, containing the module path, a Go version, and its dependency requirements, which are the other modules needed for a successful build.
If no <modulepath>
is specified, go mod init
will try to guess the module path from the directory structure, but it can also be overrided, by supplying an argument.
1 | mkdir my-project |
A go.mod
file could look like this:
1 | module cmd |
The built-in documentation provides an overview of all available go mod
commands.
1 | go help mod |