65

go mod 管理项目包

 5 years ago
source link: https://studygolang.com/articles/19832?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

golang module 管理项目包

简介

  • golang在1.11版本中引入了新的包管理工具 go mod。包管理一直是go语言的痛点。
  • 包管理的常见需求:项目依赖某个包的不同版本,依赖本地的(私有的)包等

用法

  • 个人推荐golang IDE:goland。上手快,功能强大,比idea快很多。这里用的也是goland
  • 题外话:go mod的特性让golang越来越适应工程管理的需求。解放了对$GOPATH的依赖。更加注重项目本身。
  • 进入正题:
  1. File --> New Project --> Go Module(vgo) 在location处选择自己的项目路径,路径不一定需要是$GOPATH。按需勾选vendering。Create!

    bVbrvmz?w=777&h=485

  2. 创建完之后项目名下边有go.mod

    bVbrvm5?w=510&h=257

  3. 如何在项目中定义自己需要的包,以configs包为例。右键项目名,新建文件夹,名为自己需要定义的包,此处示例为configs。如果这个包是私有的,不放到公开的github上,main函数以 import "webproject/configs" 导入包

    bVbrvpl?w=858&h=323

    bVbrvpE?w=869&h=384

  4. 如何在项目中导入第三方的包,以gin包为例。
    4.1 直接import不管用,报错如下:

    bVbrvrH?w=1041&h=438

    4.2 根据提示 Alt + Shift + Enter键或点击Sync packages。将需要的依赖写入到go.mod当中。

    bVbrvtW?w=848&h=1026

    4.3 相关的依赖顺利写入到go.mod。

    bVbrvup?w=1128&h=639

  5. 第四步中可能存在golang.org天朝网络问题,可以用 replace解决。我是直接用Proxifier解决。

总结

  • 总的来说,使用go mod进行依赖管理,还是比较令人满意的。之后再看需要,补充go mod tidy,导入其他module包等情形。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK