第二章:环境搭建¶
2.1 安装 Go¶
Linux 安装¶
# 下载 Go
wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz
# 解压到 /usr/local
sudo tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz
# 配置环境变量
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
echo 'export GOPATH=$HOME/go' >> ~/.bashrc
echo 'export PATH=$PATH:$GOPATH/bin' >> ~/.bashrc
source ~/.bashrc
# 验证安装
go version
macOS 安装¶
Windows 安装¶
2.2 环境配置¶
环境变量¶
# 查看当前配置
go env
# 设置代理(国内推荐)
go env -w GOPROXY=https://goproxy.cn,direct
# 设置私有仓库
go env -w GOPRIVATE=github.com/myorg/*
# 开启 Modules 模式
go env -w GO111MODULE=on
重要环境变量¶
| 变量 | 说明 | 默认值 |
|---|---|---|
| GOROOT | Go 安装目录 | /usr/local/go |
| GOPATH | 工作目录 | $HOME/go |
| GOPROXY | 模块代理 | https://proxy.golang.org |
| GOMODCACHE | 模块缓存 | $GOPATH/pkg/mod |
2.3 开发工具¶
VS Code 配置¶
// settings.json
{
"go.useLanguageServer": true,
"go.lintTool": "golangci-lint",
"go.formatTool": "goimports",
"go.testFlags": ["-v"],
"[go]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
}
// 推荐扩展
{
"recommendations": [
"golang.go"
]
}
GoLand¶
JetBrains 出品的 Go IDE,功能强大: - 智能代码补全 - 重构支持 - 调试器 - 版本控制集成
2.4 第一个 Go 程序¶
创建项目¶
# 创建项目目录
mkdir hello
cd hello
# 初始化模块
go mod init example.com/hello
# 创建 main.go
cat > main.go << 'EOF'
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
EOF
# 运行
go run main.go
# 编译
go build -o hello
# 运行编译产物
./hello
项目结构¶
hello/
├── go.mod # 模块定义
├── go.sum # 依赖校验
├── main.go # 主程序
├── cmd/ # 命令行工具
│ └── myapp/
│ └── main.go
├── pkg/ # 公共包
│ └── utils/
│ └── utils.go
├── internal/ # 私有包
│ └── service/
│ └── service.go
└── api/ # API 定义
└── proto/
2.5 Go Modules¶
常用命令¶
# 初始化模块
go mod init example.com/myapp
# 下载依赖
go mod download
# 整理依赖
go mod tidy
# 查看依赖
go list -m all
# 添加依赖
go get github.com/gin-gonic/gin
# 添加特定版本
go get github.com/gin-gonic/gin@v1.9.0
# 更新依赖
go get -u github.com/gin-gonic/gin
# 移除未使用的依赖
go mod tidy
go.mod 文件¶
module example.com/myapp
go 1.21
require (
github.com/gin-gonic/gin v1.9.0
github.com/go-sql-driver/mysql v1.7.0
)
require (
// 间接依赖
github.com/mattn/go-isatty v0.0.17 // indirect
)
2.6 常用工具¶
代码格式化¶
静态检查¶
# 安装 golangci-lint
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin
# 运行检查
golangci-lint run
代码生成¶
# 安装代码生成工具
go install github.com/google/wire/cmd/wire@latest
go install github.com/golang/mock/mockgen@latest
小结¶
- 使用官方安装包或包管理器安装 Go
- 配置 GOPROXY 加速模块下载
- Go Modules 是官方依赖管理方案
- VS Code + Go 扩展是轻量高效的选择