zoukankan      html  css  js  c++  java
  • Golang Vendor 包机制 及 注意事项

    现在的 Go 版本是 1.8,早在 1.5 时期,就有了 Vendor 包机制,详情可查看博文:“理解 Go 1.5 vendor”。

    遇到的问题

    个人在使用 Glide 管理 Vendor 包时(附:Golang Vendor 包管理工具 glide 使用教程),老编译不成功! 后来猛地发现,原来是我对 Vendor 包机制理解不够深入导致的。

    Glide 官方教程中提供了一个 Demo 项目结构,如下所示:

    $GOPATH/src/myProject (Your project)
      |
      |-- glide.yaml
      |
      |-- glide.lock
      |
      |-- main.go (Your main go code can live here)
      |
      |-- mySubpackage (You can create your own subpackages, too)
      |    |
      |    |-- foo.go
      |
      |-- vendor
           |-- github.com
                |
                |-- Masterminds
                      |
                      |-- ... etc.

    我改了一下,去掉了目录结构中的 myProject 文件夹,如下所示:

    $GOPATH/src
      |
      |-- glide.yaml
      |
      |-- glide.lock
      |
      |-- main.go (Your main go code can live here)
      |
      |-- mySubpackage (You can create your own subpackages, too)
      |    |
      |    |-- foo.go
      |
      |-- vendor
           |-- github.com
                |
                |-- Masterminds
                      |
                      |-- ... etc.

    然后 go build 一直提示找不到相关的包(其实 glide 已经把它下载到 vendor 目录中了) 。

    后来回过头看 “理解 Go 1.5 vendor”,里面有一段有关 Vendor 的英文介绍:

    If there is a source directory d/vendor, then, when compiling a source file within the subtree rooted at d, import "p" is interpreted as import "d/vendor/p" if that exists.

    When there are multiple possible resolutions,the most specific (longest) path wins.

    The short form must always be used: no import path can  contain “/vendor/” explicitly.

    Import comments are ignored in vendored packages.

    它的大体意思就是,当有包路径 "d/vendor/p" 时,可以使用 import "p" 的简短形式来代替! 

    其实,它还隐藏着另外一个非常重要的细节,即:

    vendor 目录不能放到 工作空间源码包目录的根目录($GOPATH/src)之下,必须放到 某个(项目)文件夹之下,如下面的  myProject 文件夹:

    $GOPATH/src/myProject (Your project)
      |
      |-- glide.yaml
      |
      |-- glide.lock
      |
      |-- main.go (Your main go code can live here)
      |
      |-- vendor
           |-- github.com
                |
                |-- Masterminds
                      |
                      |-- ... etc.
    

    好吧,接下来一切都很顺利!

    相关文章:

    【Go入门教程1】Go 安装,GOROOT,GOPATH,Go工作空间

  • 相关阅读:
    日志组件一:Log4j
    HTTPS加密那点事--轻松秒懂HTTPS非对称加密
    图解Git
    Python 迭代器 & __iter__方法
    Fiddler 抓包工具总结
    Python使用struct处理二进制(pack和unpack用法)
    Python binascii
    常见证书格式及相互转换
    MyBatis Generator 详解
    MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合
  • 原文地址:https://www.cnblogs.com/52php/p/6367738.html
Copyright © 2011-2022 走看看