package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
)
type Case struct {
Name string `json:"name"`
Summary string `json:"summary"`
Expected any `json:"expected"`
Actual any `json:"actual"`
Passed bool `json:"passed"`
}
type Report struct {
Version string `json:"version"`
Cases []Case `json:"cases"`
}
func makeCase(name, summary string, expected, actual any) Case {
return Case{
Name: name,
Summary: summary,
Expected: expected,
Actual: actual,
Passed: reflect.DeepEqual(expected, actual),
}
}
func runGo(dir string, args ...string) (string, error) {
cmd := exec.Command("go", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(), "GOPROXY=off", "GOSUMDB=off")
out, err := cmd.CombinedOutput()
return strings.TrimSpace(string(out)), err
}
func main() {
tmpRoot, err := os.MkdirTemp("", "golab-mod-*")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer os.RemoveAll(tmpRoot)
var cases []Case
// Case 1: Real offline `go mod init` and generated go.mod structure
initDir := filepath.Join(tmpRoot, "hello")
_ = os.MkdirAll(initDir, 0755)
_, initErr := runGo(initDir, "mod", "init", "example.com/hello")
goModRaw, _ := os.ReadFile(filepath.Join(initDir, "go.mod"))
goModStr := string(goModRaw)
actual1 := map[string]any{
"init_ok": initErr == nil,
"has_module_dir": strings.Contains(goModStr, "module example.com/hello"),
"has_go_122": strings.Contains(goModStr, "go 1.22"),
}
expected1 := map[string]any{
"init_ok": true,
"has_module_dir": true,
"has_go_122": true,
}
cases = append(cases, makeCase(
"mod_init_and_go_mod_structure",
"离线执行 go mod init 生成 go.mod 并核验 module 路径与 go 1.22 版本指令",
expected1, actual1,
))
// Case 2: Local replace dependency + go test + go run (100% offline)
quoteDir := filepath.Join(tmpRoot, "localquote")
_ = os.MkdirAll(quoteDir, 0755)
_, _ = runGo(quoteDir, "mod", "init", "example.com/localquote")
_ = os.WriteFile(filepath.Join(quoteDir, "quote.go"), []byte("package localquote\n\nfunc Hello() string { return \"Hello from localquote v0.1.0\" }\n"), 0644)
_, editErr := runGo(initDir, "mod", "edit",
"-require=example.com/localquote@v0.1.0",
"-replace=example.com/localquote=../localquote",
)
_ = os.WriteFile(filepath.Join(initDir, "main.go"), []byte("package main\n\nimport (\n\t\"fmt\"\n\t\"example.com/localquote\"\n)\n\nfunc Greeting() string { return localquote.Hello() }\n\nfunc main() { fmt.Println(Greeting()) }\n"), 0644)
_ = os.WriteFile(filepath.Join(initDir, "main_test.go"), []byte("package main\n\nimport \"testing\"\n\nfunc TestGreeting(t *testing.T) {\n\tgot := Greeting()\n\twant := \"Hello from localquote v0.1.0\"\n\tif got != want { t.Fatalf(\"got %q want %q\", got, want) }\n}\n"), 0644)
testOut, testErr := runGo(initDir, "test", "./...")
runOut, runErr := runGo(initDir, "run", ".")
actual2 := map[string]any{
"edit_ok": editErr == nil,
"test_ok": testErr == nil && strings.Contains(testOut, "ok"),
"run_ok": runErr == nil,
"run_output": runOut,
}
expected2 := map[string]any{
"edit_ok": true,
"test_ok": true,
"run_ok": true,
"run_output": "Hello from localquote v0.1.0",
}
cases = append(cases, makeCase(
"mod_local_replace_build_and_test",
"离线通过 replace 本地模块映射执行 go test ./... 与 go run . 验证模块依赖解析",
expected2, actual2,
))
// Case 3: go list -m all, go mod graph, go mod why
listOut, listErr := runGo(initDir, "list", "-m", "all")
graphOut, graphErr := runGo(initDir, "mod", "graph")
whyOut, whyErr := runGo(initDir, "mod", "why", "example.com/localquote")
actual3 := map[string]any{
"list_ok": listErr == nil,
"list_contains": strings.Contains(listOut, "example.com/hello") && strings.Contains(listOut, "example.com/localquote v0.1.0 => ../localquote"),
"graph_ok": graphErr == nil && strings.Contains(graphOut, "example.com/hello example.com/localquote@v0.1.0"),
"why_ok": whyErr == nil && strings.Contains(whyOut, "example.com/hello") && strings.Contains(whyOut, "example.com/localquote"),
}
expected3 := map[string]any{
"list_ok": true,
"list_contains": true,
"graph_ok": true,
"why_ok": true,
}
cases = append(cases, makeCase(
"mod_list_graph_and_why",
"离线执行 go list -m all、go mod graph 与 go mod why 查询模块依赖图与引用链路",
expected3, actual3,
))
// Case 4: Minimal Version Selection (MVS) diamond + exclude directive
mvsRoot := filepath.Join(tmpRoot, "mvs")
libDir := filepath.Join(mvsRoot, "lib")
modADir := filepath.Join(mvsRoot, "moda")
modBDir := filepath.Join(mvsRoot, "modb")
appDir := filepath.Join(mvsRoot, "app")
for _, d := range []string{libDir, modADir, modBDir, appDir} {
_ = os.MkdirAll(d, 0755)
}
_ = os.WriteFile(filepath.Join(libDir, "go.mod"), []byte("module example.com/lib\n\ngo 1.22\n"), 0644)
_ = os.WriteFile(filepath.Join(libDir, "lib.go"), []byte("package lib\n\nconst Name = \"lib\"\n"), 0644)
_ = os.WriteFile(filepath.Join(modADir, "go.mod"), []byte("module example.com/moda\n\ngo 1.22\n\nrequire example.com/lib v1.1.0\n"), 0644)
_ = os.WriteFile(filepath.Join(modADir, "a.go"), []byte("package moda\n\nimport \"example.com/lib\"\n\nfunc A() string { return lib.Name }\n"), 0644)
_ = os.WriteFile(filepath.Join(modBDir, "go.mod"), []byte("module example.com/modb\n\ngo 1.22\n\nrequire example.com/lib v1.3.0\n"), 0644)
_ = os.WriteFile(filepath.Join(modBDir, "b.go"), []byte("package modb\n\nimport \"example.com/lib\"\n\nfunc B() string { return lib.Name }\n"), 0644)
appGoMod := strings.Join([]string{
"module example.com/app",
"",
"go 1.22",
"",
"require (",
"\texample.com/moda v1.0.0",
"\texample.com/modb v1.0.0",
")",
"",
"replace (",
"\texample.com/moda => ../moda",
"\texample.com/modb => ../modb",
"\texample.com/lib => ../lib",
")",
"",
}, "\n")
_ = os.WriteFile(filepath.Join(appDir, "go.mod"), []byte(appGoMod), 0644)
_, exclEditErr := runGo(appDir, "mod", "edit", "-exclude=example.com/badmod@v1.0.0")
mvsListOut, mvsListErr := runGo(appDir, "list", "-m", "example.com/lib")
appModAfter, _ := os.ReadFile(filepath.Join(appDir, "go.mod"))
actual4 := map[string]any{
"mvs_list_ok": mvsListErr == nil,
"mvs_selected_13": strings.Contains(mvsListOut, "example.com/lib v1.3.0 => ../lib"),
"exclude_edit_ok": exclEditErr == nil && strings.Contains(string(appModAfter), "exclude example.com/badmod v1.0.0"),
}
expected4 := map[string]any{
"mvs_list_ok": true,
"mvs_selected_13": true,
"exclude_edit_ok": true,
}
cases = append(cases, makeCase(
"mod_mvs_and_exclude_semantics",
"离线构造菱形依赖验证最小版本选择(MVS)选中 v1.3.0 及 exclude 排除指令写入",
expected4, actual4,
))
report := Report{
Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
Cases: cases,
}
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(report); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
本例需在 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。
入口文件:projects/go-modules-lab/explore_modules.go
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore_modules.go,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1176.zip