Go项目如何正确导入vendor目录下第三方包的结构体并使用
问题原因
- 导包路径错误:
models.go是authentication包下的代码文件,不属于目录层级,你填写的导入路径github.com/somepackage/authentication/models不存在,正确包路径到authentication目录为止 - 类型引用未加包前缀:导入外部包的类型需要携带包名作为前缀,不能直接写
*User - Go modules模式下未开启vendor识别:默认Go modules会从模块缓存查找依赖,不会自动读取vendor目录内容
解决步骤
- 修正导入语句
将custom/custom.go中的导入代码替换为:
import "github.com/somepackage/authentication"
如果觉得包名太长可以自定义别名:
import auth "github.com/somepackage/authentication" // 后续类型引用就可以写*auth.User
- 修正所有相关的类型声明
// 函数类型定义补充包前缀 type loginFn func(string, string) (*authentication.User, error) // 自定义函数签名同步修改 func SetupGoGuardian(u, p string) (*authentication.User, error) { // 业务逻辑实现 }
- 开启vendor目录识别
执行Go相关命令时指定vendor模式,即可优先读取本地vendor目录的依赖:
# 运行项目 go run -mod=vendor ./custom # 构建项目 go build -mod=vendor ./...
验证
执行go list -mod=vendor ./custom,无报错输出即代表导包配置正确。
内容的提问来源于stack exchange,提问作者rai
相关产品推荐
相关产品推荐

