golang-mod

golang当前有两种模式

1、path

2、mod

当前以mod为例

Go Mod常用命令

go.mod文件命令

go.mod 提供了 module、require、replace 和 exclude 四个命令,如下:

命令 描述
module 语句指定包的名字(路径)
require 语句指定的依赖项模块
replace 语句可以替换依赖项模块
exclude 语句可以忽略依赖项模块

 

 

 

 

 

go mod常用命令

命令 描述
download 下载模块到本地缓存,具体可以通过命令 go env 查看,其中环境变量 GOCACHE 就是缓存的地址,如果该文件夹的内容太大,可以通过命令 go clean -cache
edit 从工具或脚本中编辑 go.mod 文件
graph 打印模块需求图
init 在当前目录下初始化新的模块
tidy 添加缺失的模块以及移除无用的模块
verify 验证依赖项是否达到预期的目的
why 解释为什么需要包或模块

使用go-mod


创建

#创建
cd projectName //进入项目
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOPRIVATE=*.zuoyebang.cc //配置私有域名 仓库优先从这里下载
go mod init projectName //创建mod配置
go get ... or go mod tidy
// 完成依赖包的加载
# 报错
go: github.com/circonus-labs/circonus-gometrics imports
github.com/circonus-labs/circonusllhist: github.com/circonus-labs/circonusllhist@v0.3.0: parsing go.mod:
        module declares its path as: github.com/openhistogram/circonusllhist
                but was required as: github.com/circonus-labs/circonusllhist
# 解决
# 其中 github.com/openhistogram/circonusllhist 是 新仓库地址
# github.com/circonus-labs/circonusllhist 是 旧仓库地址

# 下载最新的仓库地址
go get github.com/openhistogram/circonusllhist

# 接下来 编辑go.mod 将旧库的名字指向新库地址
vim go.mod
 replace (
  github.com/circonus-labs/circonusllhist v0.3.0 => github.com/openhistogram/circonusllhist v0.3.0
  // 旧仓库 版本号 => 新仓库 版本号
 )
# 然后继续开始 go get...

 

# go-mod 模式下加载本地包
package main

import "projectName/test"
// 加载逻辑: go-mod名称/目录下的具体包名
func main() {
  ...  
}

ps:

使用go-mod模式后,goland加载模式需要变更。

GOPATH设置为空

再配置上这个内容,goland就能自动加载各种包了。

原文地址:https://www.cnblogs.com/supermarx/p/15104071.html