0%

GO_Learning_HOW_TO_SET_UP_GO_PROJECT

GO Chinese Docs, TDD

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 as GOPATH;
      • src: store the source code of GO project; When we use version control tools like git , svn etc ,what only need is control the file in GOPATH\src directory;
      • pkg: store the cache file;
      • bin: store the executable file;

GO project structure

Personal

image-20210914004010297

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 :

image-20210914004028032

This way we could get others package with confidence, for example:

1
go get gihub.com/GuardingDog/GoLearning

company

image-20210914004056239

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
2
3
mkdir my-project
cd my-project
go mod init <modulepath>

A go.mod file could look like this:

1
2
3
module cmd

go 1.16

The built-in documentation provides an overview of all available go mod commands.

1
2
go help mod
go help mod init