installation
Configuration Environment
Enable Go Modules
go mod
In Go >= 1.13
only enabled by default, in Go >= 1.11
has begun to support the go mod
.
Set Environment Variables
# 启用go module
export GO111MODULE=on
# 设置GOPATH,开启go mod之后,这个目录主要用来存放依赖包
export GOPATH=~/go_modules
# 设置go代理,在运行go test/build等时会自动下载依赖
# 使用go get下载依赖需要在GOPATH中执行才会使用代理
export GOPROXY=https://goproxy.io
go mod use
In $GOPATH/src
any directory other than create a directory,
mkdir -p /home/gopher/project
cd /home/gopher/project
This directory is the root directory of your project, create a mod file in the directory management
go mod init project
If you put this project on github, then you can write when you create a file, project name for your github project
go mod init github.com/YourName/project
go.mod
The initial content cat go.mod
is:
module project
go 1.12
go.mod
Only you need to create once, in a project in the root directory of the project Go
will automatically find all the current directory 父级目录
until you find go.mod
.
Introduced on the package definition and package custom
A directory only by a defined package
比如在project项目中有了一个hello.go的文件,文中定义了package hello, 这样,当你再在project中创建了一个world.go的文件,其中定义了package world会报错,无法加载package
Each package defines, in a directory. Recommend the same directory name and package name defined in the package.
project ├── go.mod ├── hello │ ├── hello.go │ └── hello1.go ├── main.go └── world ├── world.go └── world1.go 其中hello目录中所有文件的包定义均为package hello,hello目录中所有文件的包定义均为package world
go mod management
Create a new module
# 创建了一个新的模块,初始化 `go.mod` 文件并且生成相应的描述 go mod init
Add Dependency
# build,test和其它构建代码包的命令,会在需要的时候在go.mod文件中添加新的依赖项 # 最好不要自己修改go.mod文件,因为在Go在向go.mod中添加依赖项的时候 # 同时会向go.sum中的hash对比,确定依赖是否修改。 go build go test
View all current dependencies
# 列出了当前模块所有的依赖项 go list -m all
Modify the specified dependency versions (or add a new dependency)
# 修改或添加 # go get -u 会更新依赖 # 获取指定版本的形式 go get rsc.io/[email protected] go get
Removing unused dependencies
go mod tidy