go 11以后啟用了go mod功能,用於管理依賴包。
當執行go mod init生成go.mod文件之后,golang在運行、編譯項目的時候,都會檢查依賴並下載依賴包。
在啟動了go mod之后,通過go mod下載的依賴包,不在放在GOPATH/src中,而是放到GOPATH/pkg/mod中。
比如我當前的GOPATH=/root/go,我在/root/goProjects/下新建了一個項目gProject1,並在項目下編寫了一些代碼,引用了一些第三方包:
- echo $GO111MODULE
auto
- mkdir /root/goProjects/gProject1
- cd /root/goProjects/gProject1
- vi main.go
- cat main.go
package main
import (
"log"
"github.com/toolkits/smtp"
)
func main() {
//s := smtp.New("smtp.exmail.qq.com:25", "notify@a.com", "password")
s := smtp.NewSMTP("smtp.exmail.qq.com:25", "notify@a.com", "password",false,false,false)
log.Println(s.SendMail("notify@a.com", "ulric@b.com;rain@c.com", "這是subject", "這是body,<font color=red>red</font>"))
}
- go mod init gProject1
go: creating new go.mod: module gProject1
-cat go.mod
module gProject1
go 1.12
yzc:gProj
- go run main.go
如果此時報錯:
build command-line-arguments: cannot load github.com/toolkits/smtp: cannot find module providing package github.com/toolkits/smtp
原因是因為git版本較低,go get 無法通過git下載github.com/toolkits/smtp到指定路徑。
你可以手動執行一下go get github.com/toolkits/smtp,發現會報一個類似這樣的錯誤:
# go get github.com/toolkits/smtp
go get github.com/toolkits/smtp: git ls-remote -q https://github.com/toolkits/smtp in /root/go/pkg/mod/cache/vcs/7028097e3b6cce3023c34b7ceae3657ef3f2bbb25dec9b4362813d1fadd80297: exit status 129:
usage: git ls-remote [--heads] [--tags] [-u <exec> | --upload-pack <exec>] <repository> <refs>...
就是git版本太低了,無法支撐go get運行git時的參數調用。
升級git
-
macos:
brew upgrade git -
centos6/7
Remove old git
sudo yum remove git*
centos6:
sudo yum -y install https://centos6.iuscommunity.org/ius-release.rpm
centos7:
sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm
sudo yum -y install git2u-all
再次執行go run main.go:
go: finding github.com/toolkits/smtp latest
go: downloading github.com/toolkits/smtp v0.0.0-20190110072832-af41f29c3d89
go: extracting github.com/toolkits/smtp v0.0.0-20190110072832-af41f29c3d89
2019/07/27 16:15:52 535 Error: ��ʹ����Ȩ���¼�������뿴: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
