使用protobuf生成代码import包找不到

protobuf使用import导入包找不到

前言

使用protobuf生成go代码,发现protobuf中一个import引用找不到

protobuf代码

syntax = "proto3";

package main;

import "github.com/mwitkow/go-proto-validators/validator.proto";

message Message {
    string important_string = 1 [
        (validator.field) = {regex: "^[a-z]{2,5}$"}
    ];
    int32 age = 2 [
        (validator.field) = {int_gt: 0, int_lt: 100}
    ];
}

生成的时候报错

$ protoc --govalidators_out=. --go_out=plugins=grpc:. hello.proto
github.com/mwitkow/go-proto-validators/validator.proto: File not found.
hello.proto:5:1: Import "github.com/mwitkow/go-proto-validators/validator.proto" was not found or had errors.

解决方案

我们要弄明白protoc中proto_path参数的含义

  • proto_path: 指定了在哪个目录中搜索import中导入的和要编译为.go的proto文件,可以定义多个

所以添加proto_path就可以了,指定两个地址,一个是import的地址,一个是要编译为.go的proto文件的地址

$ protoc --proto_path=. --proto_path=${GOPATH}/src --govalidators_out=. --go_out=plugins=grpc:. hello.proto
原文地址:https://www.cnblogs.com/ricklz/p/13877244.html