构建与测试¶
编译并测试你自己的 Traefik!
想从源码构建自己的 Traefik 二进制文件? 下面介绍具体方法。
构建¶
你需要:
- Docker
- make
- Go
- misspell
- shellcheck
- 如果使用 Docker Desktop,还需要 Tailscale
源码目录
建议将 Traefik 克隆到 ~/go/src/github.com/traefik/traefik 目录。
这是官方的 Go 工作区目录结构,可以确保依赖得到正确解析。
环境
通过以下命令将 GOPATH 和 PATH 变量配置到 ~/go:
export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin
为方便使用,可以将 GOPATH 和 PATH 加入 .bashrc 或 .bash_profile。
执行 $ go env,验证环境配置是否正确。
根据操作系统和环境的不同,你应当看到类似以下内容的输出:
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/<yourusername>/go"
GORACE=""
## ... and the list goes on
构建 Traefik¶
设置好 Go 环境并克隆源码仓库后,即可构建 Traefik。
$ make binary
SHA: 8fddfe118288bb5280eb5e77fa952f52def360b4 cheddar 2024-01-11_03:14:57PM
CGO_ENABLED=0 GOGC=off GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w \
-X github.com/traefik/traefik/v2/pkg/version.Version=8fddfe118288bb5280eb5e77fa952f52def360b4 \
-X github.com/traefik/traefik/v2/pkg/version.Codename=cheddar \
-X github.com/traefik/traefik/v2/pkg/version.BuildDate=2024-01-11_03:14:57PM" \
-installsuffix nocgo -o "./dist/darwin/arm64/traefik" ./cmd/traefik
$ ls dist/
traefik*
Traefik 可执行文件(traefik)位于 ./dist 目录中。
测试¶
使用 test-unit 目标运行单元测试。
使用 test-integration 目标运行集成测试。
使用 test 目标运行所有测试(单元测试和集成测试)。
$ make test-unit
GOOS=darwin GOARCH=arm64 go test -cover "-coverprofile=cover.out" -v ./pkg/... ./cmd/...
+ go test -cover -coverprofile=cover.out .
ok github.com/traefik/traefik 0.005s coverage: 4.1% of statements
Test success
开发时可以使用以下方式指定要运行的测试(仅适用于 test-integration 目标):
为 Docker Desktop 用户配置 Tailscale
在 integration 目录中创建 tailscale.secret 文件。
该文件需要包含一个 Tailscale 身份验证密钥, 建议使用临时但可重复使用的密钥。
将以下配置加入 Tailscale ACL,以自动批准 Docker 子网中容器的路由:
"autoApprovers": {
// Allow myself to automatically
// advertize routes for docker networks
"routes": {
"172.31.42.0/24": ["your_tailscale_identity"],
},
},
# Run every tests in the MyTest suite
TESTFLAGS="-test.run TestAccessLogSuite" make test-integration
# Run the test "MyTest" in the MyTest suite
TESTFLAGS="-test.run TestAccessLogSuite -testify.m ^TestAccessLog\$\$" make test-integration