天天看点

Go语言学习(九) 使用go mod管理go包

在windows环境下做的以下配置

1、创建一个工程文件夹:

dockerApiTools

2、初始化go mod

进入工程目录下运行命令:

go mod init docker.api.tools.iscas.com/v1
           

3、配置环境变量

Go语言学习(九) 使用go mod管理go包

GORROXY

修改go下载的代理镜像为国内的

GO111MODULE

为on 表示只会使用go module的方式寻找依赖包

4、编写编程示例程序

Go语言学习(九) 使用go mod管理go包

这里使用gin作为http服务器测试

package main

import (
   "github.com/gin-gonic/gin"
   "net/http"
)

func main() {
   ginServ := gin.Default()
   ginServ.Any("/hello", WebRoot)
   ginServ.Run(":8888")
}

func WebRoot(context *gin.Context) {
   context.String(http.StatusOK, "hello, world")
}

           

在没有的依赖包上使用

ALT+ENTER

下载依赖包。

导入后的

go.mod

文件:

module docker.api.tools.iscas.com/v1

go 1.17

require github.com/gin-gonic/gin v1.7.4

require (
   github.com/gin-contrib/sse v0.1.0 // indirect
   github.com/go-playground/locales v0.13.0 // indirect
   github.com/go-playground/universal-translator v0.17.0 // indirect
   github.com/go-playground/validator/v10 v10.4.1 // indirect
   github.com/golang/protobuf v1.3.3 // indirect
   github.com/json-iterator/go v1.1.9 // indirect
   github.com/leodido/go-urn v1.2.0 // indirect
   github.com/mattn/go-isatty v0.0.12 // indirect
   github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
   github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
   github.com/ugorji/go/codec v1.1.7 // indirect
   golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
   golang.org/x/sys v0.0.0-20200116001909-b77594299b42 // indirect
   gopkg.in/yaml.v2 v2.2.8 // indirect
)

           

5、其他的go mod命令

1、下载所有的依赖:
go mod download

2、移除不需要的依赖包:
go mod tidy

3、移除制定的依赖包:
go mod edit --droprequire=packagepath

4、发布新版本
go mod edit --module=yourpackagename/v2

           

6、在离线环境可以使用本地的文件

在go.mod中

replace github.com/gin-gonic/gin => C:\Users\admin\go\pkg\mod\github.com\gin-gonic\[email protected]

require github.com/gin-gonic/gin v1.7.4

           

go包的下载位置可以通过go env 命令查到的GOMODCACHE

Go语言学习(九) 使用go mod管理go包