golang module

。_饼干妹妹 提交于 2019-12-24 16:16:08

一、使用手册

1. 使用方法:

go mod <command> [arguments]

2. 具体命令

download: download modules to local cache(下载依赖包)
edit: edit go.mod from tools or scripts(编辑 go.mod)
graph: print module requirement graph(打印模块依赖图)
init: initialize new module in current directory(在当前目录初始化 mod)
tidy: add missing and remove unused modules(拉取缺少的模块,移除不用的模块)
vendor: make vendored copy of dependencies(将依赖复制到vendor下)
verify: verify dependencies have expected content(验证依赖是否正确)
why: explain why packages or modules are needed(解释为什么需要依赖)

二、使用前准备

1. 终端输入

export GO111MODULE=on

2. GO111MODULE 说明

GO111MODULE 有三个值:offonauto(默认值)

(1)off,go命令行将不会支持module功能,寻找依赖包的方式将会沿用旧版本那种通过vendor目录或者GOPATH模式来查找

(2)on,go命令行会使用modules,而一点也不会去GOPATH目录下查找

(3)auto,默认值,go命令行将会根据当前目录来决定是否启用module功能;这种情况下可以分为两种情形:

当前目录在GOPATH/src之外且该目录包含go.mod文件

当前文件在包含go.mod文件的目录下面

三、具体示例

1. 创建一个新项目

(1)在 GOPATH 目录之外新建一个目录,并使用 go mod init 初始化生成 go.mod 文件

$ go mod init test

go: creating new go.mod: module test

$ cat go.mod

module test

go 1.13

(2)go.mod 提供了module, require、replace和exclude 四个命令

module 语句指定包的名字(路径)

require 语句指定的依赖项模块

replace 语句可以替换依赖项模块

exclude 语句可以忽略依赖项模块

2. 添加依赖

# test.go
package main

import (
	"net/http"
	"github.com/labstack/echo"
)

func main() {
	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})
	e.Logger.Fatal(e.Start(":1323"))
}

 

执行 go run test.go 运行代码会发现 go mod 会自动查找依赖自动下载

$ cat go.mod
module test
go 1.13
require (
	github.com/labstack/echo v3.3.10+incompatible
	github.com/labstack/gommon v0.3.0 // indirect
	golang.org/x/crypto v0.0.0-20191219195013-becbf705a915 // indirect
)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!