Go Module实战测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Nassue_sn/article/details/86704644

go modules

官方提倡的包管理方式(go 1.11增加),乃至项目管理机制,使用go mod管理项目,将可以绕开GO项目必须放置到GOPATH目录的约束,以下将与大家一起测试

实战测试

1.新建文件夹

$> mkdir test
$> cd test

2.初始化

$> go mod init test
go: creating new go.mod: module test

3.新建main.go文件(这里导入go-redis库作为示例)

$> cat main.go
package main

import (
	"fmt"

	"github.com/go-redis/redis"
)

func Client() {
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	pong, errs := client.Ping().Result()
	fmt.Println(pong, errs)

	err := client.Set("key", "value", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := client.Get("key").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("key", val)

	val2, err := client.Get("key2").Result()
	if err == redis.Nil {
		fmt.Println("key2 does not exist")
	} else if err != nil {
		panic(err)
	} else {
		fmt.Println("key2", val2)
	}
	// Output: key value
	// key2 does not exist
}

func main() {
	fmt.Println("使用外部库测试!")
	Client()
}

4.尝试更新依赖

$> go mod tidy
出现以下报错(golang被墙导致)
go: golang.org/x/net@v0.0.0-20180906233101-161cd47e91fd: unrecognized import path "golang.org/x/net" (https fetch: Get https://golang.org/x/net?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
go: golang.org/x/sync@v0.0.0-20180314180146-1d60e4601c6f: unrecognized import path "golang.org/x/sync" (https fetch: Get https://golang.org/x/sync?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
go: golang.org/x/text@v0.3.0: 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: i/o timeout)
go: golang.org/x/sys@v0.0.0-20180909124046-d0be0721c37e: unrecognized import path "golang.org/x/sys" (https fetch: Get https://golang.org/x/sys?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
go: error loading module requirements

5.根据提示依次替换为github资源

go mod edit -replace=golang.org/x/sync@v0.0.0-20180314180146-1d60e4601c6f=github.com/golang/sync@v0.0.0-20180314180146-1d60e4601c6f
go mod edit -replace=golang.org/x/sys@v0.0.0-20180909124046-d0be0721c37e=github.com/golang/sys@v0.0.0-20180909124046-d0be0721c37e
go mod edit -replace=golang.org/x/net@v0.0.0-20180906233101-161cd47e91fd=github.com/golang/net@v0.0.0-20180906233101-161cd47e91fd
go mod edit -replace=golang.org/x/text@v0.3.0=github.com/golang/text@v0.3.0

6.再次尝试更新依赖(成功)

$> go mod tidy

7.查看当前文件列表

$> ls
go.mod  go.sum  main.go

8.本地启动redis服务,监听端口6379

9.测试是否正确执行

$> go run main.go
使用外部库测试!
PONG <nil>
key value
key2 does not exist
展开阅读全文

没有更多推荐了,返回首页