go mod 简介及使用

超、凢脫俗 2023-10-05 22:42 117阅读 0赞

目的

记述 go mod 使用

介绍

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

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

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

可以使用 go help mod 查看 go mod 的使用文档

  1. Go mod provides access to operations on modules.
  2. Note that support for modules is built into all the go commands,
  3. not just 'go mod'. For example, day-to-day adding, removing, upgrading,
  4. and downgrading of dependencies should be done using 'go get'.
  5. See 'go help modules' for an overview of module functionality.
  6. Usage:
  7. go mod <command> [arguments]
  8. The commands are:
  9. download download modules to local cache
  10. edit edit go.mod from tools or scripts
  11. graph print module requirement graph
  12. init initialize new module in current directory
  13. tidy add missing and remove unused modules
  14. vendor make vendored copy of dependencies
  15. verify verify dependencies have expected content
  16. why explain why packages or modules are needed
  17. Use "go help mod <command>" for more information about a command.

实战

一、开启 GO111MODULE

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

  1. go env -w GO111MODULE=auto

二、新建项目

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

  1. mkdir go01

三、初始化

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

  1. # 进入项目目录
  2. cd go01
  3. # 初始化mod,将其mod标志设置为xzbd.com/go01
  4. go mod init xzbd.com/go01

运行后,输出

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

四、整理项目依赖

根据建议运行推荐命令go mod tidy整理项目依赖。也可以不用运行,因为项目此时没有使用任何依赖

五、创建go01.go文件

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

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. fmt.Println("hello go mod")
  7. }

六、运行

运行项目前可以执行go mod tidy整理项目资源,
本例中依然可以不用执行此命令,因为依赖的包fmt是go语言的标准包。

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

总结

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

项目结构:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读

    相关 GO mod入门

    借鉴帖子,特别感谢: 作者:会飞的鲶鱼 链接:https://www.jianshu.com/p/c666ebdb462b   Go Module是Go官方在1.11