24

GO Modules 使用

 5 years ago
source link: https://studygolang.com/articles/18560?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

旧项目迁移,打算使用GO Modules 作为依赖管理。

go版本 1.12

私人依赖包,如何处理

1. 创建模块的目录 ,并伸出go.mod 文件

mkdir modules
go mod  init modules

2. 创建自己的package目录 如 base

module
    |--- main.go
    |---go.mod
    |---base
            |---testBase.go

其中main.go 的内容

package main
import "modules/base"
func main(){
    base.Test()
}

testBase.go 的文件内容

package base 
import "fmt"
func Test(){
    fmt.Println("Bast Test)
}

可以看到 在任何模块的个人package的引用都必须使用 module/ 开头的路径地址。

再任何文件的 import时,go会再当前目录向上级目录逐级查找go.mod文件,比较mod文件中的 module 名称是否与查找的引用包路径匹配,然后按照引用路径查找。

针对之前没有有使用过go mod 的项目,需要的操作步骤是

1.将原来的src 下的代码拷贝到某个GOPATH之外的目录中,比如 server

2.在server目录下 ,go mod init server ,当前模块的根目录即是 server

3.将其他文件里的个人定义的包的引用路径改为 server/XXX ,以便于可以从模块的根目录找到

4. 在命令行 执行 go build server ,可以刷新所有的引用包且编译出可执行文件

针对国内墙,无法取到某些package的情况

1. 使用 https://goproxy.io ,通过设置

FRjUNfe.png!web

2. 通过go mod  replace命令

比如golang.org/x 下面的package是无法再国内直接获取的,可以通过修改go.mod文件将地址替换为 github上的镜像,基本都可以找到

在生产的go.mod 文件里添加

replace (
     golang.org/x/crypto => github.com/golang/crypto latest
     golang.org/x/net => github.com/golang/net latest
    golang.org/x/sync => github.com/golang/sync latest
     golang.org/x/sys => github.com/golang/sys
     golang.org/x/text => github.com/golang/text 
 )

这样就可以从GitHub上获取对于的包文件

相关文档:

1. https://roberto.selbach.ca/intro-to-go-modules/

这是 Roberto Selbach 大神写的这篇 Step by step的 go mod入门文章,非常好理解

2. https://github.com/golang/go/wiki/Modules

go mod的官方文档,想了解的多一点最好还是通读一下

3. https://roberto.selbach.ca/go-proxies/

最后还有一篇介绍GOPROXY的文章,比较适合对go mod熟悉之后再看


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK