Go Mod 配置

本文主要介绍Go mod 的配置过程中遇到的问题和使用。也是我在初次使用中遇到的问题,做个记录。如何开启go mod 配置?如何解决go get 超时问题?Goland使用 go mod 包管理时,怎么引入github上的包?Goland使用 go ...

本文主要介绍Go mod 的配置过程中遇到的问题和使用。也是我在初次使用中遇到的问题,做个记录。

  1. 如何开启go mod 配置?
  2. 如何解决go get 超时问题?
  3. Goland使用 go mod 包管理时,怎么引入github上的包?
  4. Goland使用 go mod 包管理时,怎么引入自己的包?

一、开启go mod 配置

  1. 终端中使用 go env 查看 GO111MODULE 配置情况
GO111MODULE=off,go命令行将不会支持module功能,寻找依赖包的方式将会沿用旧版本那种通过vendor目录或者GOPATH模式来查找。
GO111MODULE=on,go命令行会使用modules,而一点也不会去GOPATH/src目录下查找。 (pkg 包都存放在 $GOPATH/pkg 下)
GO111MODULE=auto,默认值,go命令行将会根据当前目录来决定是否启用module功能。(pkg 包都存放在 $GOPATH/pkg 下)

我本人使用的是 GO111MODULE=auto , 可以兼容以前的项目(没使用go mod的项目)。

为了说清楚问题,我自己建了一个项目。

  1. 我建了自己的项目模块redisStudy
  2. 在项目根目录(…/redisStudy/ )执行了 go mod init redisStudy 命令 ,初始化mod 成功,生成了go.mod 文件。 项目的各个包目录下,不要再执行了 go mod init命令了。这个命令只用在需要使用go mod 管理的项目模块的根目录执行一次就可以了。
  3. 新建了我自己的两个包,logicreids和LoginQueue

    下面是我写的一个简单的获取 redisi连接的程序
package logicredis

import (
	"github.com/go-redis/redis"
	"log"
)

var redisClient *redis.Client

func NewRedisClient(url string, db, poolSize int) (*redis.Client, error){
	opt, err := redis.ParseURL(url)

	if poolSize > 0 {
		opt.PoolSize = poolSize
	}
	if db > 0 {
		opt.DB = db
	}
	if err != nil {
		log.Printf("new redis client url:%v error:%v", url, err)
		return nil, err
	}
	redisClient := redis.NewClient(opt)
	pong, err := redisClient.Ping().Result()

	if err != nil {
		log.Printf("redis client pong:%v error:%v", pong, err)
		return nil, err
	}

	log.Printf("[redis] new redis url:%v pong:%v", url, pong)

	return redisClient, nil
}

func RedisClient() *redis.Client{
	return redisClient
}

注意这里我使用了import “github.com/go-redis/redis” ,这里我并没有下载包。所以一定会找不到。
按照过去的做法,要编译logicredis.go需要执行go get 命令 下载github.com/go-redis/redis包到 $GOPATH/src。但是,使用了新的包管理就不在需要这样做了。
直接 go build logicredis.go
go 会自己动下载依赖包(这里可能问遇到 下载超时的问题,如需解决,请看问题二“go get 超时问题”)。

使用Go的包管理方式,依赖的包下载到哪里了?还在GOPATH里吗?
不在,使用Go的包管理方式,依赖的第三方包被下载到了$GOPATH/pkg/mod路径下。

二、go get 超时问题

go env
--------
...
GOPROXY="https://proxy.golang.org,direct"
...

如果是这个代理,基本就会超时,修改为 七牛的代理即可
终端执行 set GOPROXY=“https://goproxy.cn” 然后go env查看是否设置成功

go env
--------
...
GOPROXY="https://goproxy.cn"
...

三、Goland使用 go mod 导入 github上的包
首先 启用 Goland 的 go mod ,File->setting->Go->Go Modules
Enable Go modules integration 打上勾

如果 不进行如上配置,在引用 github上的包时,就会报错,提示找不到路径,如下图。

四、Goland使用 go mod 导入 自己的包

  1. 新建一个项目

  2. 在项目根目录下使用 “go mod init mod名” 初始化 mod,初始化成功后会在执行命令的根目录下出现go.mod文件。

  3. 然后在包B引入自己的包A的的时候,import mod名/A 即可。

  4. 我建了自己的项目模块redisStudy

  5. 在项目根目录(…/redisStudy/ )执行了 go mod init redisStudy 命令 ,初始化mod 成功,生成了go.mod 文件。 项目的各个包目录下,不要再执行了 go mod init命令了。这个命令只用在需要使用go mod 管理的项目的根目录执行一次就可以了。

  6. 新建了我自己的两个包,logicreids和LoginQueue

  7. 我在LoginQueue 需要引用 logicreids 时 使用 import “redisStudy/logicredis” 即可。

参考:

参考文章链接 https://zhuanlan.zhihu.com/p/60703832

本文标题为:Go Mod 配置