Go11-模块管理与项目结构

📅 2026/7/16 21:27:38
Go11-模块管理与项目结构
第10章模块管理与项目结构10.1 Go Modules 基础Go Modules 是 Go 1.11 引入的依赖管理系统是现代 Go 项目的标准。初始化模块# 创建新项目mkdirmyprojectcdmyproject go mod init myproject# 或者使用 GitHub 路径go mod init github.com/username/myprojectgo.mod 文件module github.com/username/myproject go 1.22 require ( github.com/gin-gonic/gin v1.9.1 github.com/go-sql-driver/mysql v1.7.1 ) require ( // 依赖项 )常用命令# 添加依赖go get github.com/gin-gonic/gin# 更新依赖go get-ugithub.com/gin-gonic/gin# 删除未使用的依赖go mod tidy# 下载所有依赖go mod download# 查看依赖图go mod graph# 查看为什么需要某个依赖go mod why github.com/some/dependency# 验证依赖go mod verify10.2 项目结构标准项目布局myproject/ ├── cmd/ # 可执行文件 │ └── server/ │ └── main.go ├── internal/ # 私有包不可被外部导入 │ ├── handler/ # HTTP 处理器 │ │ └── user.go │ ├── service/ # 业务逻辑 │ │ └── user.go │ ├── repository/ # 数据访问层 │ │ └── user.go │ └── model/ # 数据模型 │ └── user.go ├── pkg/ # 公共包可被外部导入 │ └── utils/ │ └── helpers.go ├── api/ # API 定义 │ └── swagger.yaml ├── configs/ # 配置文件 │ └── config.yaml ├── scripts/ # 脚本 ├── tests/ # 集成测试 ├── docs/ # 文档 ├── go.mod ├── go.sum ├── Makefile └── README.md分层架构┌─────────────────────────────────────┐ │ HTTP/gRPC 层 │ │ (handler, middleware) │ ├─────────────────────────────────────┤ │ 业务逻辑层 │ │ (service) │ ├─────────────────────────────────────┤ │ 数据访问层 │ │ (repository) │ ├─────────────────────────────────────┤ │ 数据库/缓存 │ └─────────────────────────────────────┘10.3 包管理包的可见性// pkg/utils/helpers.gopackageutils// 公开函数首字母大写funcPublicFunc()string{returnpublic}// 私有函数首字母小写funcprivateFunc()string{returnprivate}内部包// internal/config/config.gopackageconfig// 只能被 internal 目录下的包导入typeConfigstruct{DBHoststringDBPortint}循环依赖// 错误包 A 依赖包 B包 B 又依赖包 A// 解决方案// 1. 提取公共接口到第三个包// 2. 使用接口解耦// 3. 重构代码结构10.4 配置管理使用环境变量packageconfigimport(osstrconv)typeConfigstruct{PortintDBHoststringDBPortintDebugbool}funcLoad()*Config{returnConfig{Port:getEnvInt(PORT,8080),DBHost:getEnv(DB_HOST,localhost),DBPort:getEnvInt(DB_PORT,3306),Debug:getEnvBool(DEBUG,false),}}funcgetEnv(key,fallbackstring)string{ifvalue:os.Getenv(key);value!{returnvalue}returnfallback}funcgetEnvInt(keystring,fallbackint)int{ifvalue:os.Getenv(key);value!{ifi,err:strconv.Atoi(value);errnil{returni}}returnfallback}funcgetEnvBool(keystring,fallbackbool)bool{ifvalue:os.Getenv(key);value!{ifb,err:strconv.ParseBool(value);errnil{returnb}}returnfallback}使用配置文件packageconfigimport(osgopkg.in/yaml.v2)typeConfigstruct{Server ServerConfigyaml:serverDB DBConfigyaml:db}typeServerConfigstruct{Portintyaml:portHoststringyaml:host}typeDBConfigstruct{Hoststringyaml:hostPortintyaml:portUserstringyaml:userPasswordstringyaml:passwordNamestringyaml:name}funcLoadConfig(pathstring)(*Config,error){data,err:os.ReadFile(path)iferr!nil{returnnil,err}varconfig Config erryaml.Unmarshal(data,config)iferr!nil{returnnil,err}returnconfig,nil}10.5 构建与部署Makefile.PHONY: build run test clean # 构建 build: go build -o bin/server cmd/server/main.go # 运行 run: go run cmd/server/main.go # 测试 test: go test -v ./... # 清理 clean: rm -rf bin/ # 代码检查 lint: golangci-lint run # 交叉编译 build-linux: GOOSlinux GOARCHamd64 go build -o bin/server-linux cmd/server/main.go build-windows: GOOSwindows GOARCHamd64 go build -o bin/server.exe cmd/server/main.goDockerfile# 多阶段构建 FROM golang:1.22-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED0 GOOSlinux go build -o server cmd/server/main.go FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --frombuilder /app/server . CMD [./server]10.6 练习创建一个标准的 Go 项目结构编写 Makefile 管理常用命令实现配置文件加载功能编写 Dockerfile 进行多阶段构建10.7 下一章下一章我们将学习 Go 语言的测试与基准测试。