在Go中强制执行特定的导入路径 [英] Forcing a Specific Import Path in Go

查看:316
本文介绍了在Go中强制执行特定的导入路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<>新的Go程序员在这里 - 道歉,如果这是磨损的领土,但我的谷歌搜索还没有找到我要找的答案。

简版:我可以作为核心Go项目的外部程序员强制我的软件包以特定名称导入。如果是这样,怎么做?



长版本:我最近试图从遵循GitHub仓库,使用以下去获取

  go get github.com/golang/crypto 

该软件包正确地下载到我的工作区中,但是当我尝试导入它时,出现以下错误:


$ go run main.go main.go:10:2:目录/path/to/go/src/github.com/golang/crypto/bcrypt中的代码需要导入golang.org/x/crypto/bcrypt


即东西告诉去这个包应该被导入 golang.org/x/crypto/bcrypt 。这让我想起了我真正想要的是

  go get golang.org/x/crypto/bcrypt 

我想在我自己的软件包中做类似的事情 - Go包装内置了这个功能吗?或者 crypto / bcrypt 的作者是否在运行时检测并拒绝无效的包导入名称?

解决方案

是的,它的内置,我似乎无法找到实现文档(这是1.5或1.6中的一个相对较新的功能),但语法是:

 包名//导入您的自定义路径

示例: https://github.com/ golang / crypto / blob / master / bcrypt / bcrypt.go#L7

//编辑

此功能的设计文档为 https://docs.google.com / document / d / 1jVFkZTcYbNLaTxXD9OcGfn7vYv5hWtPx9 - lTx1gPMs / edit

//编辑

@JimB指出 https://golang.org/cmd/go/#hdr-Import_path_checking ,以及go1.4发行说明: https://golang.org/doc/go1.4#canonicalimports


New Go programmer here -- apologies if this is well worn territory, but my google searching hasn't turned up the answer I'm looking for.

Short Version: Can I, as a programmer external to the core Go project, force my packages to be imported with a specific name. If so, how?

Long Version: I recently tried to install the bcrypt package from the following GitHub repository, with the following go get

go get github.com/golang/crypto

The package downloaded correctly into my workspace, but when I tried to import it, I got the following error

$ go run main.go main.go:10:2: code in directory /path/to/go/src/github.com/golang/crypto/bcrypt expects import "golang.org/x/crypto/bcrypt"

i.e. something told Go this package was supposed to be imported with golang.org/x/crypto/bcrypt. This tipped me off that what I actually wanted was

go get golang.org/x/crypto/bcrypt

I'd like to do something similar in my own packages — is this functionality built into Go packaging? Or are the authors of crypto/bcrypt doing something at runtime to detect and reject invalid package import names?

解决方案

Yes it's built in, I can't seem to find the implementation document (it's a relatively new feature in 1.5 or 1.6) however the syntax is:

package name // import "your-custom-path"

Example: https://github.com/golang/crypto/blob/master/bcrypt/bcrypt.go#L7

// edit

The design document for this feature is https://docs.google.com/document/d/1jVFkZTcYbNLaTxXD9OcGfn7vYv5hWtPx9--lTx1gPMs/edit

// edit

@JimB pointed out to https://golang.org/cmd/go/#hdr-Import_path_checking, and in the go1.4 release notes: https://golang.org/doc/go1.4#canonicalimports

这篇关于在Go中强制执行特定的导入路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆