目的

记述 go mod 使用

介绍

Go mod 是 Go 1.11 提出的开发包管理工具,在此之前go发布过许多包管理方案,但都强依赖于环境变量GOPATH,存在诸多缺点,不易于项目管理。

Go 之于 mod ,好比 Java 之于 maven 、 Js 之于 npm 。

它的出现使得Go语言项目脱离了对GOPATH的强依赖,为Go语言后期快速成长提供了强有力的保障。

go help mod
Go mod provides access to operations on modules.

Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.

Usage:

        go mod <command> [arguments]

The commands are:

        download    download modules to local cache
        edit        edit go.mod from tools or scripts
        graph       print module requirement graph
        init        initialize new module in current directory
        tidy        add missing and remove unused modules
        vendor      make vendored copy of dependencies
        verify      verify dependencies have expected content
        why         explain why packages or modules are needed

Use "go help mod <command>" for more information about a command.

实战

一、开启 GO111MODULE

GO111MODULE 是 go 开启 mod 包管理工具的一个环境配置,共有三个配置项,分别是 off 、on 、auto 。开启mod包管理模式,可以使用选项 on 或 auto。

go env -w  GO111MODULE=auto

二、新建项目

找一个合适的地方,新建项目 go01

	mkdir go01

三、初始化

进入项目目录,使用 init 初始化 go01 项目


# 进入项目目录
cd go01

# 初始化mod,将其mod标志设置为xzbd.com/go01
go mod init xzbd.com/go01

运行后,输出

go: creating new go.mod: module xzbd.com/go01
go: to add module requirements and sums:
        go mod tidy

四、整理项目依赖

go mod tidy

五、创建go01.go文件

创建 go01.go 文件,其内容如下:


package main

import (
	"fmt"
)

func main() {
	fmt.Println("hello go mod")
}

六、运行

go mod tidyfmt

运行 go run go01.go 即可打印信息 hello go mod

总结

go mod 使用还是相对简单的,笔者在此做了简单记录

项目结构: