记录一下如何运行一个来自 GitHub 等渠道的现成的 Go 项目.

情况分两种:

  1. 有 go.mod 通过 module 方式开发的,
  2. 无 go.mod, 通过 GOPATH 旧版本方式开发的

module 方式开发

Go 1.11 and 1.12 include preliminary support for modules, Go 1.16 Modules on by default.

对于有 go.mod 的项目:

  1. git clone xx 克隆项目到本地

  2. go get 根据 go.mod 下载对应的包

  3. 是否有 main 函数

    1. 如果有

      go run *.go 直接运行,不生成可执行文件 go build *.go 编译为可执行二进制文件,然后 ./main 运行

    2. 如果没有

      一般库没有 main 函数,每个文件会有对应的 test 函数, 可以使用 vscode 的 test 模块进行运行测试,也可以命令行

      直接测试全部文件: go test

      指定某个,单独测试: go test xx_test.go

      注意:如果该单个测试文件使用了其他包的函数等,会报错

      1
      2
      command-line-arguments
      xxx.go. xxvaribale undefined

      这种情况需要在 go test xx_test.go 之后再加上报错的那些所在的 go 文件

GOPATH 开发

GOPATH 开发的,没有 go.mod 的基本是比较老的项目了,一般还需要处理库的版本问题.

  1. git clone xx 克隆项目到本地

改为 module 形式:

  1. go mod init mymodule_name 在包文件下,创建 mod

    mymodule_name 是你自己写的模块名字,自己定义即可

    go.mod 示例:

    1
    2
    module mymodule_name
    go 1.19

    然后,需要遍历每个 go 文件,找到引用的外部的包,写到 mod 里面来

    1. go mod tidy

      该命令检查代码的包依赖,并将其加入 go.mod, 并移除没有用到的,并创建 go.sum 但是如果有旧包找不到,就会报错,不会添加. 所以如果有旧包,可以根据其输出先将正常的包及其版本手动添加到 go.mod 中,然后可以根据下载的项目的 commit 时间,去找那个旧包大概时间的 commit 值

      1
      2
      3
      4
      5
      6
      7
      8
      module mymodule_name

      go 1.19

      require (
      github.com/btcsuite/btcd v0.0.0-20181123190223-3dcf298fed2d
      github.com/sirupsen/logrus v1.9.0
      )

      对于第一个包,这种需要指定 commit 的旧版本包,后面的版本号自己是写不出来的,先直接不写这个包. 通过 go get github.com/btcsuite/btcd@commit_value 来将其添加到 go mod 中,(go get 也会更新 go.mod, go.sum)

  2. go mod tidy 检查,并创建 `go.sum``

  3. 最后,参考上面的 是否有 main 函数 的部分就好了

不改为 module 形式[未测试]

直接 go get 默认下载源码导入的依赖的最新版本,如果后续有包报错,再删除包,根绝 commit 值 go get

others

go mod tidy:

This command goes through the go.mod file to resolve dependencies:

  1. delete the packages that are not needed
  2. download those needed
  3. update the go.sum

git clone 与 go get

git clone 下载仓库项目, go get 根据项目中导入的包下载最新包或者根据 go.mod 下载指定版本的包.

The git clone command will clone a repo into a newly created directory, while go get downloads and installs the packages named by the import paths, along with their dependencies.

参考

go test 进行单元测试时,出现 undefined 方法或者 command-line-arguments [build failed]解决方案_love666666shen 的博客-CSDN 博客_go test undefined