Golang Module 实战

Pip 爽惯了到了 Go 是真的头疼,于是要彻底了解一下

前言

  • 在python中,一时pip install 一时爽,一直install 一直爽
  • 在Java中也有maven和gradle等优秀成熟的依赖版本管理工具
  • 虽然从go1.12开始接触go语言(go module在>=go1.11中存在),因此也没有经历过那段艰难的时刻,但是还是对于其包管理很迷茫
  • go getgo depgo mod
  • 官方文档

使用

Get Start

  • 在默认情况下,$GOPATH 并不支持go modules,因此要通过如下命令将go modules开启

    1
    export GO111MODULE=on
  • 使用go mod init 初始化.mod 文件

  • 使用go mod tidy 安装缺失的依赖库并会自动去除无用的依赖然后更新依赖到当前版本

一些命令

1
2
3
4
5
6
7
go mod init # 初始化.mod文件
go mod tidy # 安装缺失依赖并去除无用依赖更新有用依赖
go list -m all # 列出当前module的依赖
go get <module_name>[@version] # 获取依赖module
go get -u <module_name> # 更新module
go list -m -versions <module_name> # 列出包当前的所有可用版本
go build / go test # 在编译过程中会根据.mod文件加入依赖

问题来了

  1. 出现verifying xxx 的报错,导致依赖下载不下来怎么办?

    GOPROXY你值得拥有

    • Go 1.11 在支持go module 的同时也加入了GOPROXY 环境变量,为官方依赖源无法下载的包提供第三方依赖代理

    • 可通过一下方式对下载代理进行配置

      1
      2
      3
      4
      export http_proxy=http://proxyAddress:port
      export https_proxy=http://proxyAddress:port

      export all_proxy=http://proxyAddress:port
    • 为避免每次都是用上述方法,可将配置放入profile中,在每次启动bash 终端时会自动运行

      1
      2
      3
      # ~/.bash_profile
      export http_proxy=http://proxyAddress:port
      export https_proxy=http://proxyAddress:port

补充知识

  1. bash_profile vs bashrc
    • .bash_profile 会在login shell启动时自动执行
    • .bashrc 会在bash启动的shell打开前自动执行
  2. login shell & interactive shell & non-interactive shell
    • login shell是当你通过键入身份信息/ssh方式登入的shell窗口,其依次会执行
      • .profile
      • .bash_profile
      • .bash_login
    • interactive shell 当你使用如bash 就会激活ineractive shell
    • non-interactive shell 当你使用如sh 运行脚本
0%