Golang Module Vanity URLs的使用与配置

Golang Module Vanity URLs的使用与配置 你好, 我想为我的所有项目使用 Go 模块的 Vanity URL,目前有两个项目。

项目 Go 模块 仓库
hnotes hellerwach.com/go/hnotes github.com/hellerwach/hnotes
webring hellerwach.com/go/webring github.com/hellerwach/webring

我决定使用设置 Vanity URL 的常规方式,即一个小的 HTML 文件。这些文件位于我服务器上的指定位置,据我所知,它们遵循 go get 的约定和标准。

文件树:

| /
|- go/
|  |- hnotes
|  |- webring
|-...

下载一个项目(hnotes)工作得很好:

go install hellerwach.com/go/hnotes@latest

然而,另一个项目却不行。使用与上面相同的命令,但指定表格中的模块标识符时,输出:

go install hellerwach.com/go/webring@latest
go: downloading hellerwach.com/go/webring v1.2.0
go: hellerwach.com/go/webring@latest: hellerwach.com/go/webring@v1.2.0: parsing go.mod:
        module declares its path as: hellerwach.com/go/hnotes
                but was required as: hellerwach.com/go/webring

我注意到 Go 正在下载版本 1.2.0,这是 hnotes 仓库中的最新版本,而 webring 的最新版本是 1.0.0。

经过一天的反复尝试和彻底查阅搜索引擎结果的多页内容后,我实在不知道该怎么办了。你们有人知道是什么原因吗?


更多关于Golang Module Vanity URLs的使用与配置的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang Module Vanity URLs的使用与配置的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


问题出在 webring 项目的 go.mod 文件中声明的模块路径不正确。根据错误信息,webringgo.mod 文件里写的是 module hellerwach.com/go/hnotes,但实际应该声明为 module hellerwach.com/go/webring

这是因为 Go 工具链在解析模块时,会检查 go.mod 中声明的模块路径是否与请求的路径匹配。如果不匹配,就会报错。

解决方案:

  1. 检查 webring 项目根目录下的 go.mod 文件,确保第一行是:
module hellerwach.com/go/webring
  1. 如果之前已经发布了错误的版本,需要修正后发布新版本:
# 在 webring 项目中
go mod edit -module hellerwach.com/go/webring
git add go.mod
git commit -m "fix: correct module path"
git tag v1.0.1
git push origin v1.0.1
  1. 验证 vanity URL 配置是否正确: 访问 https://hellerwach.com/go/webring 应该返回:
<!DOCTYPE html>
<html>
<head>
    <meta name="go-import" content="hellerwach.com/go/webring git https://github.com/hellerwach/webring">
    <meta name="go-source" content="hellerwach.com/go/webring _ https://github.com/hellerwach/webring/tree/main{/dir} https://github.com/hellerwach/webring/blob/main{/dir}/{file}#L{line}">
</head>
<body>
    Go module: <a href="https://hellerwach.com/go/webring">hellerwach.com/go/webring</a>
</body>
</html>
  1. 清理本地缓存后重新测试:
go clean -modcache
go install hellerwach.com/go/webring@latest

示例代码:

正确的 webring/go.mod 文件应该类似这样:

module hellerwach.com/go/webring

go 1.21

require (
    // 依赖声明
)

// 其他配置

如果问题仍然存在,检查是否有缓存的错误版本:

go list -m -versions hellerwach.com/go/webring

这会列出所有已知版本,确保没有缓存旧的错误版本。

回到顶部