Golang中无法从其他文件导入包的解决方法
Golang中无法从其他文件导入包的解决方法 我有一个可以导出的 .proto 文件,其中包含一个消息定义:
syntax = "proto3";
package domain;
option go_package = "BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE/internal/gRPC/domain";
message Repoistory{
int64 id = 1;
string name = 2;
int64 userId = 3;
bool isPrivate = 4;
}
以及另一个 .proto 文件,它从第一个文件中导入 Repository:
syntax = "proto3";
package service;
option go_package = "BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE/internal/gRPC/service";
import "github.com/MyWorkSpace/lets_Go/BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE/internal/proto-files/domain/repository.proto";
//RepositoryService Definition
service RepositoryService {
rpc add (domain.Repository) returns (AddRepositoryResponse);
}
message AddRepositoryResponse {
domain.Repository addedRepository = 1;
Error error = 2;
}
message Error {
string code = 1;
string message = 2;
}
但不幸的是,当我尝试使用以下命令安装时:
protoc --go_out=. repository-service.proto
我总是遇到这个错误:
github.com/MyWorkSpace/lets_Go/BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE/internal/proto-files/domain/repository.proto: 文件未找到。
repository-service.proto:7:1: 导入“github.com/MyWorkSpace/lets_Go/BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE/internal/proto-files/domain/repository.proto”未找到或存在错误。
repository-service.proto:15:5: “domain.Repository” 未定义。
repository-service.proto:11:14: “domain.Repository” 未定义。
基本上是说它找不到我的文件。我真的不确定问题出在哪里,因为我已经多次检查了路径,但仍然看不出问题所在。
这是我尝试导入的文件的路径:
C:\Users\justi\src\github.com\MyWorkSpace\lets_Go\BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE\internal\proto-files\domain
更多关于Golang中无法从其他文件导入包的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
感谢。这个路径更好。我之前的方案变得太复杂了。
我有太多文件了。我猜这就是为什么我遇到这么大问题的原因。
你确定文件名是 repository.proto 并且没有拼写错误吗?
可能是因为你执行 protoc 命令的位置很重要,因为导入路径是相对的。
文件路径是: C:\Users\justi\src\github.com\MyWorkSpace\lets_Go\BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE\internal\proto-files\domain\repository.proto
并且我是在另一个文件所在的文件夹中执行 protoc 命令。
问题在于protoc命令没有正确指定proto文件的导入路径。protoc需要知道如何解析import语句中的路径。你需要使用-I或--proto_path参数来指定proto文件的根目录。
假设你的项目结构如下:
BITBUCKET-REPOSITORY-MANAGEMENT-SERVICE/
├── internal/
│ ├── proto-files/
│ │ ├── domain/
│ │ │ └── repository.proto
│ │ └── service/
│ │ └── repository-service.proto
在repository-service.proto所在的目录中执行以下命令:
protoc -I=../../.. --go_out=. repository-service.proto
或者更明确地指定路径:
protoc --proto_path=C:\Users\justi\src\github.com\MyWorkSpace\lets_Go --go_out=. repository-service.proto
如果你有多个导入路径,可以指定多个-I参数:
protoc -I=. -I=../../.. --go_out=. repository-service.proto
在Windows上,路径需要使用反斜杠:
protoc --proto_path=C:\Users\justi\src\github.com\MyWorkSpace\lets_Go --go_out=. repository-service.proto
另外,建议在import语句中使用相对路径而不是绝对路径。修改repository-service.proto中的import语句:
import "internal/proto-files/domain/repository.proto";
然后从项目根目录执行:
protoc --proto_path=. --go_out=. internal/proto-files/service/repository-service.proto
这样protoc就能正确找到导入的文件了。


