Skip to content

Missing import in generated .pb.gw.go file when rpc response message is imported in .proto #6207

@theJenix

Description

@theJenix

🐛 Bug Report

protoc-gen-grpc-gateway fails to generate necessary imports for response types when a service method returns a message type from a different package/proto file and uses response_body in the gRPC API Configuration YAML.

To Reproduce

  1. Create a proto file defining a service in package foo:
// foo.proto
syntax = "proto3";
package foo;

import "bar/bar.proto";

service FooService {
    rpc GetFoo(GetFooRequest) returns (bar.BarResponse);
}

message GetFooRequest {}
  1. Create a proto file defining the response type in package bar:
 // bar/bar.proto
 syntax = "proto3";
 package bar;

 message BarResponse {
     repeated string items = 1;
 }
  1. Create a gRPC API Configuration YAML file (api_config.yaml):
type: google.api.Service
config_version: 3

http:
  rules:
    - selector: foo.FooService.GetFoo
      get: /v1/foo
      response_body: items
  1. Generate gateway code with protoc-gen-grpc-gateway using the API configuration:
protoc -I . \
    --grpc-gateway_out . \
    --grpc-gateway_opt logtostderr=true \
    --grpc-gateway_opt grpc_api_configuration=api_config.yaml \
    foo.proto bar/bar.proto

Expected behavior

The generated foo.pb.gw.go file should include an import for the bar package since bar.BarResponse is referenced in the response type assertion within the XXX_ResponseBody() method:

  import (
      "bar"  // This import should be generated
      // ... other imports
  )

  type response_FooService_GetFoo_0 struct {
      proto.Message
  }

  func (m response_FooService_GetFoo_0) XXX_ResponseBody() interface{} {
      response := m.Message.(*bar.BarResponse)  // Uses bar package
      return response.Items
  }

Actual Behavior

The generated code is missing the import for the bar package, resulting in a compilation error:

foo.pb.gw.go:168:26: undefined: bar

Your Environment

  • protoc-gen-grpc-gateway version: v2.11.3 (also present in latest main branch)
  • protoc version: libprotoc 3.x+
  • Go version: 1.16+
  • Operating system: macOS / Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions