在做 go 开发, 如果是使用 go1.11 版本, 相信大家都会使用到 go mod 做为依赖管理, 因为 go mod 可以设置代理,国外的包,轻松下载. 但是在某一天你使用公司自建的 gitlab ,需要引用 gitlab 上面的依赖包,就需要做一些设置才会正常
go mod tidy
,否则会出现无法引用的问题. 本文介绍一下如何操作.
适用于 window, linux 环境, 本人没 macOSX
你将学到:
- 如何设置 go mod 代理
- 如何设置 go env GOPRIVATE 变量
- 如何在代码里引用自建的 gitlab 依赖代码
设置 go mod 代理
linux, window 设置
|
|
实践
假定私有 gitlab 仓库地址为:
http://mygit.sgfoot.com/
(注意只支持http, 不支持https)
创建一个 gitlab 依赖代码
- 仓库地址HTTP:
http://mygit.sgfoot.com/common.git
- 仓库地址SSH:
git@mygit.sgfoot.com/common.git
- git 下载
|
|
-
创建 util.go 文件
必须在这个目录下创建文件 $GOPATH/src/mygit.sgfoot.com/common
1 2 3 4 5 6 7 8
package common import "time" func Today() string { return time.Now().Format("2006-01-02 15:04:05") }
-
使用
go mod init
如果没有外部依赖可以不使用 go mod 也是可以的.
1 2
# 直接回车 go mod init
会在项目的根目录下生成 go.mod 文件, 第一行必须是你的网站域名+你的项目路径. 也就是可以在浏览器里找到这个项目. 否则后续无法使用
go mod tidy
命令.go.mod 文件内容
1
module mygit.sgfoot.com/common
-
使用
go mod tidy
1 2
module mygit.sgfoot.com/common go 1.15
-
使用 git tag
为什么使用 tag, 方便其它项目引用不同版本号.
1 2
git add . && git commit -m "new hello" && git push -u origin master git tag v1.0.0 && git push --tag
-
git tag 扩展学习
创建一个工程项目
引用上面的
mygit.sgfoot.com/common
里的方法
- 创建 helloworld 项目
- 仓库地址HTTP:
http://mygit.sgfoot.com/helloworld.git
- 仓库地址SSH:
git@mygit.sgfoot.com/helloworld.git
- git 下载(可以是任意目录下)
|
|
-
创建 main.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package main import ( "github.com/gin-gonic/gin" "mygit.sgfoot.com/common" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "msg":"hello world", "today": common.Today(), }) }) r.Run(":8000") }
-
使用
go mod init
这里可以自定义 mod name
1 2
# 直接回车 go mod init helloworld
go.mod 文件内容
1
module helloworld
-
设置 go env GOPRIVATE
设置 gitlab 不走代理
1
go env -w GOPRIVATE=mygit.sgfoot.com
go get 不走 https
注意使用版本号.
1
go get -v -insecure mygit.sgfoot.com/common@v1.0.0
-
使用
go mod tidy
1 2 3 4 5 6 7
module helloworld go 1.15 require ( github.com/gin-gonic/gin v1.6.3 mygit.sgfoot.com/common v1.0.0 )
简约总结
1. 设置 GOPRIVATE
|
|
2. 使用-insecure
忽略 https
|
|
3. 保存 git 输入的帐号和密码
|
|