You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地pkgsite是否支持可运行示例?运行时为何请求公共代理?

本地pkgsite运行示例时请求公共代理的问题排查

问题背景

  • 本地可正常运行的Go示例代码:
func Example_should_be_runnable() {
    o := bytes.NewBufferString("")

    // RootCmd() just wraps &cobra.Command
    cmd := RootCmd()
    cmd.SetOut(o)
    cmd.SetArgs([]string{"--myarg=blah"})

    err := cmd.Execute()
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(o)
    // Output:
    // expected_output
}
  • 本地启动pkgsite后,网页运行示例出现如下错误:
go: github.com/me/myproj@v0.0.0: reading https://proxy.golang.org/github.com/me/myproj/@v/v0.0.0.mod: 404 Not Found
    server response:
    not found: github.com/me/myproj@v0.0.0: invalid version: git ls-remote -q origin in /tmp/gopath/pkg/mod/cache/vcs/177f425a899fd5149a7c1317bd8fa47cefb9929d4ba6abf74aad8c54d873f458: exit status 128:
        fatal: could not read Username for 'https://github.com': terminal prompts disabled
    Confirm the import path was entered correctly.
    If this is a private repository, see https://golang.org/doc/faq#git_https for additional information.
  • 核心疑问:
    • pkgsite运行示例时是否在尝试从公共代理https://proxy.golang.org拉取私有包?
    • 这是否属于pkgsite的bug?
    • 为什么其他GoDoc文档链接(如[mypackage.PkgExamples]格式)能正常指向本地地址http://127.0.0.1:8080,而运行示例却请求公共代理?

原因分析与解决方向

  1. pkgsite运行示例默认走公共代理
    pkgsite运行示例时,会在隔离的临时环境中构建并执行代码,默认继承Go模块的全局代理配置。即使包在本地,它依然会尝试通过公共代理拉取对应版本——因为它无法自动识别你的本地包是未发布的私有项目。

  2. 这是设计逻辑,并非bug
    其他GoDoc链接正常指向本地,是因为pkgsite处理文档链接时仅解析本地包的符号和引用,无需构建执行代码;但运行示例需要完整构建依赖链,此时Go模块工具会按照默认配置去公共代理查找版本信息。

  3. 可行的解决办法

  • 启动pkgsite时指定GOPROXY=direct,强制跳过公共代理,直接从本地或版本控制系统拉取依赖:
    GOPROXY=direct pkgsite
    
  • 若为私有仓库,可同时配置GONOSUMDB跳过私有模块的校验:
    GONOSUMDB=github.com/me/* GOPROXY=direct pkgsite
    
  • 启动pkgsite时添加-local参数,指定本地模块路径,让pkgsite优先加载本地模块:
    pkgsite -http=127.0.0.1:8080 -local github.com/me/myproj
    

内容的提问来源于stack exchange,提问作者red888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:27:10