golang / protobuf

Go support for Google's protocol buffers
BSD 3-Clause "New" or "Revised" License
9.64k stars 1.58k forks source link

How can I import a pre-compiled proto from another package? #1602

Open JoyCood opened 3 months ago

JoyCood commented 3 months ago

https://github.com/golang/protobuf/issues/721#issue-365297780

hi, i follow the step, but it's not work! anyone would help me here?

the error is: can not import common package:

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
//  protoc-gen-go v1.31.0
//  protoc        v4.25.0
// source: order.proto

package order

import (
    common "../common"
    protoreflect "google.golang.org/protobuf/reflect/protoreflect"
    protoimpl "google.golang.org/protobuf/runtime/protoimpl"
    reflect "reflect"
    sync "sync"
)

Makefile:

GOPATH:=$(shell go env GOPATH)

.PHONY: proto
proto:
    @protoc -I. --proto_path=./proto/common --micro_out=./proto/common --go_out=:./proto/common code.proto
    @protoc -I. --proto_path=./proto/order --micro_out=./proto/order --go_out=:./proto/order order.proto

env:

$ protoc --version
libprotoc 25.0

$ protoc-gen-go --version
protoc-gen-go.exe v1.31.0

common.proto:

syntax="proto3";
package common;
option go_package="../common";

enum ErrorCode {
  SUCCESS = 0;
  CREATE_ORDER_FAILED = 40001;
}

order.proto:

syntax = "proto3";
package order;
option go_package = "../order";

import "proto/common/code.proto";

service OrderService {
  rpc CreateOrder(CreateOrderReq) returns(CreateOrderResp);
}

message CreateOrderReq {
}

message CreateOrderResp {
}
puellanivis commented 3 months ago

Try not to use relative paths for go package imports.

JoyCood commented 3 months ago

Try not to use relative paths for go package imports.

thanks your response, the relative paths is generate by protoc-gen-go, how to fixed this issues?

puellanivis commented 3 months ago

The relative paths come from your proto code:

option go_package = "../order";
neild commented 3 months ago

The go_package option in your .proto file should be set to the full, non-relative import path of the Go package that will contain the generated code for that file.