go语言中如何安装第3方的包

0 阅读2分钟

go第三方包的安装地址

image

然后引入第三方的包

1,初始化项目 go mod init 项目名称
2,在项目中使用这个包,下载依赖 go mod tidy

package main

import (
	"fmt"
	"github.com/shopspring/decimal"  // 引入这个包
)

func main() {
	price, err := decimal.NewFromString("136.02")
	if err != nil {
		panic(err)
	}
	fmt.Println(price)
}

执行go mod tidy 安装依赖报错

day01.go PS D:\study\goxm>  go mod tidy

go: finding module for package github.com/shopspring/decimal

go: goStudy imports

github.com/shopspring/decimal: module github.com/shopspring/decimal: Get " https://proxy.golang.org/github.com/shopspring/decimal/@v/list ": dial tcp 142.250.197.241:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 

报错原因 :Go 默认从proxy.golang.org (Google 服务器)下载第三方包,该地址在国内被屏蔽,连接超时。 修复方式 :执行一条命令把代理换成国内镜像(永久生效,已写入 Go 环境配置):

go env -w GOPROXY=https://goproxy.cn,direct  

goproxy.cn :七牛云维护的国内 Go 模块镜像
,direct :镜像里没有的包再回源直连
以后所有go mod tidy 、go get 都会走国内镜像,不会再出现这个超时错误。go.sum 和 go.mod 也已自动更新并加入了decimal v1.4.0 依赖。

解决办法, 当前项目下设置代理
go env -w GOPROXY=goproxy.cn,direct
image

当我们成功运行 go mod tidy
当前目录下,会多一个 go sum这样一个文件
image

这个时候时候第3方包就不会报错了

package main

import (
	"fmt"

	"github.com/shopspring/decimal"
)

func main() {
	price, err := decimal.NewFromString("136.02")
	if err != nil {
		panic(err)
	}
	fmt.Println(price)
}

安装第3方包的步骤

1、go mod init 项目名称; 表示初始化这个项目
2、在需要的文件中引入第3方的包

import (
	"fmt"
	"github.com/shopspring/decimal"
)

3、go mod tidy 进行下载依赖,这个时候就会现在这个文件中使用到的第3方的包
4、运行项目

如果运行别人的项目

在运行别人项目的时候,我们看见别人的项目文件是这样的

package main
import (
	"fmt"
	"github.com/shopspring/decimal"
)
func main() {
	price, err := decimal.NewFromString("136.02")
	if err != nil {
		panic(err)
	}
	fmt.Println(price)
}

由于我们本地没有安装依赖,因此需要执行
go mod init 项目名称; 表示初始化这个项目
然后执行 go mod tidy 进行下载依赖
最后运行项目