试用 go mod
(金庆的专栏 2018.12)
Go 1.11 支持 module.
代码不需要在 GOPATH/src 目录下。
先初始化模块,生成 `go.mod`
E:\tempλ mkdir -p testmod\helloE:\tempλ cd testmod\hello\E:\temp\testmod\helloλ go mod init github.com/jinq0123/hellogo: creating new go.mod: module github.com/jinq0123/hello创建 `hello.go`
package mainimport ( "fmt" "rsc.io/quote")func main() { fmt.Println(quote.Hello())}构建时报 `golang.org/x/text` 连不上:
E:\temp\testmod\helloλ go buildgo: golang.org/x/text@v0.0.0-20170915032832-14c0d48ead0c: unrecognized import path "golang.org/x/text" (https fetch: Get https://golang.org/x/text?go-get=1: dial tcp 216.239.37.1:443: connectex:A socket operation was attempted to an unreachable network.)go: error loading module requirements`go.mod` 添加
replace golang.org/x/text => github.com/golang/text v0.3.0然后构建就成功了:
E:\temp\testmod\helloλ go buildgo: finding github.com/golang/text v0.3.0go: downloading rsc.io/sampler v1.3.0go: downloading github.com/golang/text v0.3.0E:\temp\testmod\helloλ hello.exeHello, world.如果不加版本号,则会报错:
go.mod:9: replacement module without version must be directory path (rooted or starting with ./ or ../)Go 1.11.1 replace 还有问题,仍会试图连接原地址。目前版本 1.11.4 可以用。
参考:
https://github.com/golang/go/wiki/Modules