Zoe
Zoe
返回博客

搭建自己的 Go mod 仓库

4 分钟阅读
Golangmod

最早在接触到自定义域名的Go包是Uber的go.uber.org/zap,当时感觉很酷。 这种包的方式有几个优点:

  • 包名短,易于使用
  • 品牌(装B)标识,很酷

所以最近研究了下,准备自己搭建一个类似的自己的域名的Go仓库: go.zoe.im

原理

go get在获取包时,会向将包名作为URL发送https的的GET请求, 然后解析响应HTML内容中Meta元素go-importgo-source

例如,

<!DOCTYPE html>
<html>
	<head>
		<meta name="go-import" content="go.zoe.im/x git https://github.com/jiusanzhou/x" />
		<meta name="go-source" content="go.zoe.im/x https://github.com/jiusanzhou/x https://github.com/jiusanzhou/x/tree/master{/dir} https://github.com/jiusanzhou/x/tree/master{/dir}/{file}#L{line}">
		<meta http-equiv="refresh" content="0; url=https://github.com/jiusanzhou/x">
	</head>
	<body>
		Nothing to see here. Please <a href="https://github.com/jiusanzhou/x">move along</a>.
	</body>
</html>

go-import的内容为<包名> <scm> <scm_url>。 所以代码依然还是托管在Github上。只不过,包名换成了自己的域名。

实现

想实现上诉的HTML内容返回,我们可以有2中方案,

  1. HTTP server 动态返回
  2. HTML static 内容托管

serverstatic2中方式的优缺点都很明显,

方案 优点 缺点
server 1. 无需管理包 1. 需要部署和维护服务
static 1. 部署简单无需服务器 1. 需要手动添加包

对于这2中方案都不复杂也无需做取舍,都实现一下,用户按需使用即可。

给他取个名字叫做gopkg好了。 定义配置文件如下,

name: Zoe's golang packages
description: Zoe's golang packages
metadata:
host: go.zoe.im
base:
theme:
packages:
- name: gopkg
  type: git
  schema: https
  path: github.com/jiusanzhou/gopkg
- name: x
  path: github.com/jiusanzhou/x
  sub:
  - name: cli

代码实现很简单,基本上围绕这个配置来展开生成HTML文件了。

注意,当前没有实现server

完整的代码可以查看gopkg仓库

实际使用

为了确保服务长期使用的稳定,我使用静态文件的形式。这样我只需要定期给DNS续费就可以了。

我将我自己使用go.zoe.im托管在go.zoe.im仓库

先在master分支上添加一个CNAME文件,内容为go.zoe.im,并做好正确的DNS解析。

如果,我需要添加库,只需修改master分支下的gopkg.yaml文件, 下面是我现在全部库的配置,

name: Zoe's golang packages
description: Zoe's golang packages
host: go.zoe.im
packages:
- name: gopkg
  path: github.com/jiusanzhou/gopkg
  sub:
  - name: cmd
- name: knife-go
  path: github.com/jiusanzhou/knife-go
  sub:
  - name: config
  - name: config/options
  - name: convert
  - name: pool
  - name: util
- name: x
  path: github.com/jiusanzhou/x
  sub:
  - name: sh
  - name: cli
  - name: cli/opts
  - name: httputil
- name: surferua
  path: github.com/jiusanzhou/surferua
- name: injgo
  path: github.com/jiusanzhou/injgo
  sub:
  - name: cmd/injgo
  - name: pkg/w32
- name: unipaw
  path: github.com/jiusanzhou/unipaw

Github的Action会自动运行gopkg gen来生成,所以的HTML内容,并推送到gh-pages分支。

然后就可以使用了。比如,我需要安装go.zoe.im/x库,像这样子就可以啦。

go get go.zoe.im/x

如果你也想自己搭建一个类似的,你可以参考,go.zoe.im仓库中的.github/workflows/main.ymlgopkg.yaml

Zoe

Zoe

全栈开发 · AI 工具制造者 · Go / Flutter / Rust · 开源偏执狂

https://zoe.im

评论