From 183caa70c6a3f5e53fe2e31b9a3d13dcf1b65d86 Mon Sep 17 00:00:00 2001 From: Johan Brandhorst Date: Sun, 17 May 2020 20:15:14 +0100 Subject: [PATCH] all: replace all uses of golang/protobuf/proto We have to keep using the old ptypes, descriptor and plugin packages since rules_go forces us to use them. Eventually rules_go should move to the new API and we can purge the use of the golang/protobuf package altogether. --- examples/internal/helloworld/BUILD.bazel | 2 +- .../internal/helloworld/helloworld.pb.gw.go | 2 +- examples/internal/integration/BUILD.bazel | 4 +- examples/internal/integration/client_test.go | 2 +- .../internal/integration/integration_test.go | 536 ++++++++----- examples/internal/proto/examplepb/BUILD.bazel | 3 +- .../examplepb/a_bit_of_everything.pb.gw.go | 2 +- .../proto/examplepb/echo_service.pb.gw.go | 2 +- .../proto/examplepb/flow_combination.pb.gw.go | 2 +- .../examplepb/non_standard_names.pb.gw.go | 2 +- .../examplepb/response_body_service.pb.gw.go | 2 +- .../internal/proto/examplepb/stream.pb.gw.go | 2 +- .../unannotated_echo_service.pb.gw.go | 2 +- .../proto/examplepb/use_go_template.pb.gw.go | 2 +- .../proto/examplepb/wrappers.pb.gw.go | 2 +- .../internal/proto/standalone/BUILD.bazel | 2 +- .../unannotated_echo_service.pb.gw.go | 2 +- examples/internal/server/BUILD.bazel | 1 - .../internal/server/a_bit_of_everything.go | 57 +- internal/codegenerator/BUILD.bazel | 4 +- internal/codegenerator/parse_req.go | 8 +- internal/codegenerator/parse_req_test.go | 10 +- internal/descriptor/BUILD.bazel | 7 +- internal/descriptor/grpc_api_configuration.go | 11 +- .../descriptor/grpc_api_configuration_test.go | 15 - internal/descriptor/registry.go | 20 +- internal/descriptor/registry_test.go | 16 +- internal/descriptor/services.go | 19 +- internal/descriptor/services_test.go | 59 +- internal/descriptor/types.go | 158 ++-- internal/descriptor/types_test.go | 20 +- internal/generator/generator.go | 6 +- protoc-gen-grpc-gateway/BUILD.bazel | 2 +- .../internal/gengateway/BUILD.bazel | 4 +- .../internal/gengateway/generator.go | 12 +- .../internal/gengateway/generator_test.go | 22 +- .../internal/gengateway/template_test.go | 154 ++-- protoc-gen-grpc-gateway/main.go | 12 +- protoc-gen-swagger/BUILD.bazel | 2 +- .../internal/genswagger/BUILD.bazel | 8 +- .../internal/genswagger/generator.go | 43 +- .../internal/genswagger/template.go | 148 ++-- .../internal/genswagger/template_test.go | 751 +++++++++--------- protoc-gen-swagger/main.go | 12 +- runtime/BUILD.bazel | 7 +- runtime/convert.go | 58 +- runtime/convert_test.go | 103 +-- runtime/errors_test.go | 65 +- runtime/handler.go | 20 +- runtime/handler_test.go | 2 +- runtime/marshal_httpbodyproto.go | 4 +- runtime/marshal_httpbodyproto_test.go | 9 +- runtime/marshal_json_test.go | 14 +- runtime/marshal_jsonpb.go | 71 +- runtime/marshal_jsonpb_test.go | 316 +++++--- runtime/marshal_proto.go | 3 +- runtime/marshal_proto_test.go | 6 +- runtime/marshaler_registry.go | 11 +- runtime/mux.go | 2 +- runtime/proto2_convert.go | 2 +- runtime/query.go | 20 +- runtime/query_test.go | 42 +- 62 files changed, 1576 insertions(+), 1331 deletions(-) diff --git a/examples/internal/helloworld/BUILD.bazel b/examples/internal/helloworld/BUILD.bazel index 392944eee64..1db4735e414 100644 --- a/examples/internal/helloworld/BUILD.bazel +++ b/examples/internal/helloworld/BUILD.bazel @@ -30,10 +30,10 @@ go_library( deps = [ "//internal/utilities:go_default_library", "//runtime:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/examples/internal/helloworld/helloworld.pb.gw.go b/examples/internal/helloworld/helloworld.pb.gw.go index 868e0950c39..856a88a3e95 100644 --- a/examples/internal/helloworld/helloworld.pb.gw.go +++ b/examples/internal/helloworld/helloworld.pb.gw.go @@ -13,13 +13,13 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/integration/BUILD.bazel b/examples/internal/integration/BUILD.bazel index e9e27238fc4..58525248230 100644 --- a/examples/internal/integration/BUILD.bazel +++ b/examples/internal/integration/BUILD.bazel @@ -18,13 +18,13 @@ go_test( "//examples/internal/server:go_default_library", "//runtime:go_default_library", "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library_gen", - "@com_github_golang_protobuf//proto:go_default_library", "@com_github_google_go_cmp//cmp:go_default_library", "@go_googleapis//google/rpc:status_go_proto", "@io_bazel_rules_go//proto/wkt:empty_go_proto", "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", "@org_golang_google_grpc//codes:go_default_library", + "@org_golang_google_protobuf//encoding/protojson:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", "@org_golang_google_protobuf//testing/protocmp:go_default_library", ], ) diff --git a/examples/internal/integration/client_test.go b/examples/internal/integration/client_test.go index 2312aeec700..a4304ccd644 100644 --- a/examples/internal/integration/client_test.go +++ b/examples/internal/integration/client_test.go @@ -111,7 +111,7 @@ func testABEClientCreate(t *testing.T, cl *abe.APIClient) { want.EnumValueAnnotation.String(), ) if err != nil { - t.Errorf("cl.Create(%#v) failed with %v; want success", want, err) + t.Fatalf("cl.Create(%#v) failed with %v; want success", want, err) } if resp.Uuid == "" { t.Errorf("resp.Uuid is empty; want not empty") diff --git a/examples/internal/integration/integration_test.go b/examples/internal/integration/integration_test.go index c34062886b9..056422a1f49 100644 --- a/examples/internal/integration/integration_test.go +++ b/examples/internal/integration/integration_test.go @@ -18,20 +18,22 @@ import ( "testing" "time" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" + emptypb "github.com/golang/protobuf/ptypes/empty" "github.com/google/go-cmp/cmp" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/examplepb" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/pathenum" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/sub" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/genproto/protobuf/field_mask" + statuspb "google.golang.org/genproto/googleapis/rpc/status" + fieldmaskpb "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/grpc/codes" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/testing/protocmp" ) +var marshaler = &runtime.JSONPb{} + func TestEcho(t *testing.T) { if testing.Short() { t.Skip() @@ -101,8 +103,8 @@ func testEcho(t *testing.T, port int, apiPrefix string, contentType string) { } var msg examplepb.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.Id, "myid"; got != want { @@ -134,8 +136,8 @@ func testEchoOneof(t *testing.T, port int, apiPrefix string, contentType string) } var msg examplepb.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.GetLang(), "golang"; got != want { @@ -167,8 +169,8 @@ func testEchoOneof1(t *testing.T, port int, apiPrefix string, contentType string } var msg examplepb.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.GetStatus().GetNote(), "golang"; got != want { @@ -200,8 +202,8 @@ func testEchoOneof2(t *testing.T, port int, apiPrefix string, contentType string } var msg examplepb.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.GetNo().GetNote(), "golang"; got != want { @@ -215,14 +217,13 @@ func testEchoOneof2(t *testing.T, port int, apiPrefix string, contentType string func testEchoBody(t *testing.T, port int, apiPrefix string) { sent := examplepb.SimpleMessage{Id: "example"} - var m jsonpb.Marshaler - payload, err := m.MarshalToString(&sent) + payload, err := marshaler.Marshal(&sent) if err != nil { - t.Fatalf("m.MarshalToString(%#v) failed with %v; want success", payload, err) + t.Fatalf("marshaler.Marshal(%#v) failed with %v; want success", payload, err) } apiURL := fmt.Sprintf("http://localhost:%d/%s/example/echo_body", port, apiPrefix) - resp, err := http.Post(apiURL, "", strings.NewReader(payload)) + resp, err := http.Post(apiURL, "", bytes.NewReader(payload)) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return @@ -240,8 +241,8 @@ func testEchoBody(t *testing.T, port int, apiPrefix string) { } var received examplepb.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &received); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &received); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if diff := cmp.Diff(received, sent, protocmp.Transform()); diff != "" { @@ -325,8 +326,8 @@ func testABECreate(t *testing.T, port int) { } var msg examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if msg.Uuid == "" { @@ -410,13 +411,12 @@ func testABECreateBody(t *testing.T, port int) { }, } apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) - var m jsonpb.Marshaler - payload, err := m.MarshalToString(&want) + payload, err := marshaler.Marshal(&want) if err != nil { - t.Fatalf("m.MarshalToString(%#v) failed with %v; want success", want, err) + t.Fatalf("marshaler.Marshal(%#v) failed with %v; want success", want, err) } - resp, err := http.Post(apiURL, "application/json", strings.NewReader(payload)) + resp, err := http.Post(apiURL, "application/json", bytes.NewReader(payload)) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", apiURL, err) return @@ -434,8 +434,8 @@ func testABECreateBody(t *testing.T, port int) { } var msg examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if msg.Uuid == "" { @@ -513,9 +513,12 @@ func testABEBulkCreate(t *testing.T, port int) { Amount: 10, }, } - var m jsonpb.Marshaler - if err := m.Marshal(w, &want); err != nil { - t.Fatalf("m.Marshal(%#v, w) failed with %v; want success", want, err) + out, err := marshaler.Marshal(&want) + if err != nil { + t.Fatalf("marshaler.Marshal(%#v, w) failed with %v; want success", want, err) + } + if _, err := w.Write(out); err != nil { + t.Fatalf("w.Write() failed with %v; want success", err) } if _, err := io.WriteString(w, "\n"); err != nil { t.Errorf("w.Write(%q) failed with %v; want success", "\n", err) @@ -542,9 +545,9 @@ func testABEBulkCreate(t *testing.T, port int) { t.Logf("%s", buf) } - var msg empty.Empty - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + var msg emptypb.Empty + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } @@ -574,12 +577,17 @@ func testABEBulkCreateWithError(t *testing.T, port int) { } { time.Sleep(1 * time.Millisecond) - want := examplepb.ABitOfEverything{ + want := &examplepb.ABitOfEverything{ StringValue: fmt.Sprintf("strprefix/%s", val), } - var m jsonpb.Marshaler - if err := m.Marshal(w, &want); err != nil { - t.Fatalf("m.Marshal(%#v, w) failed with %v; want success", want, err) + out, err := marshaler.Marshal(want) + if err != nil { + t.Errorf("marshaler.Marshal(%#v, w) failed with %v; want success", want, err) + return + } + if _, err := w.Write(out); err != nil { + t.Errorf("w.Write() failed with %v; want success", err) + return } if _, err := io.WriteString(w, "\n"); err != nil { t.Errorf("w.Write(%q) failed with %v; want success", "\n", err) @@ -613,9 +621,9 @@ func testABEBulkCreateWithError(t *testing.T, port int) { t.Logf("%s", buf) } - var msg spb.Status - if err := json.Unmarshal(buf, &msg); err != nil { - t.Fatalf("json.Unmarshal(%s, &msg) failed with %v; want success", buf, err) + var msg statuspb.Status + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Fatalf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) } } @@ -641,8 +649,8 @@ func testABELookup(t *testing.T, port int) { } var want examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &want); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &want) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &want); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &want) failed with %v; want success", buf, err) return } @@ -661,8 +669,8 @@ func testABELookup(t *testing.T, port int) { } var msg examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if diff := cmp.Diff(msg, want, protocmp.Transform()); diff != "" { @@ -687,7 +695,7 @@ func TestABEPatch(t *testing.T) { port := 8088 // create a record with a known string_value and int32_value - uuid := postABE(t, port, examplepb.ABitOfEverything{StringValue: "strprefix/bar", Int32Value: 32}) + uuid := postABE(t, port, &examplepb.ABitOfEverything{StringValue: "strprefix/bar", Int32Value: 32}) // issue PATCH request, only updating string_value req, err := http.NewRequest( @@ -711,11 +719,11 @@ func TestABEPatch(t *testing.T) { } // issue GET request, verifying that string_value is changed and int32_value is not - getRespBody := getABE(t, port, uuid) - if got, want := getRespBody.StringValue, "strprefix/foo"; got != want { + getRestatuspbody := getABE(t, port, uuid) + if got, want := getRestatuspbody.StringValue, "strprefix/foo"; got != want { t.Errorf("string_value= %q; want %q", got, want) } - if got, want := getRespBody.Int32Value, int32(32); got != want { + if got, want := getRestatuspbody.Int32Value, int32(32); got != want { t.Errorf("int_32_value= %d; want %d", got, want) } } @@ -732,59 +740,89 @@ func TestABEPatchBody(t *testing.T) { for _, tc := range []struct { name string - originalValue examplepb.ABitOfEverything - input examplepb.UpdateV2Request - want examplepb.ABitOfEverything + originalValue *examplepb.ABitOfEverything + input *examplepb.UpdateV2Request + want *examplepb.ABitOfEverything }{ { name: "with fieldmask provided", - originalValue: examplepb.ABitOfEverything{ - Int32Value: 42, - StringValue: "rabbit", - SingleNested: &examplepb.ABitOfEverything_Nested{Name: "some value that will get overwritten", Amount: 345}, + originalValue: &examplepb.ABitOfEverything{ + Int32Value: 42, + StringValue: "rabbit", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Name: "some value that will get overwritten", + Amount: 345, + }, }, - input: examplepb.UpdateV2Request{Abe: &examplepb.ABitOfEverything{ - StringValue: "some value that won't get updated because it's not in the field mask", - SingleNested: &examplepb.ABitOfEverything_Nested{Amount: 456}, - }, UpdateMask: &field_mask.FieldMask{Paths: []string{"single_nested"}}}, - want: examplepb.ABitOfEverything{ - Int32Value: 42, - StringValue: "rabbit", - SingleNested: &examplepb.ABitOfEverything_Nested{Amount: 456}, + input: &examplepb.UpdateV2Request{ + Abe: &examplepb.ABitOfEverything{ + StringValue: "some value that won't get updated because it's not in the field mask", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Amount: 456, + }, + }, + UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"single_nested"}}, + }, + want: &examplepb.ABitOfEverything{ + Int32Value: 42, + StringValue: "rabbit", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Amount: 456, + }, }, }, { // N.B. This case passes the empty field mask to the UpdateV2 method so falls back to PUT semantics as per the implementation. name: "with empty fieldmask", - originalValue: examplepb.ABitOfEverything{ - Int32Value: 42, - StringValue: "some value that will get overwritten", - SingleNested: &examplepb.ABitOfEverything_Nested{Name: "value that will get empty", Amount: 345}, + originalValue: &examplepb.ABitOfEverything{ + Int32Value: 42, + StringValue: "some value that will get overwritten", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Name: "value that will get empty", + Amount: 345, + }, }, - input: examplepb.UpdateV2Request{Abe: &examplepb.ABitOfEverything{ - StringValue: "some updated value because the fieldMask is nil", - SingleNested: &examplepb.ABitOfEverything_Nested{Amount: 456}, - }, UpdateMask: &field_mask.FieldMask{}}, - want: examplepb.ABitOfEverything{ - StringValue: "some updated value because the fieldMask is nil", - SingleNested: &examplepb.ABitOfEverything_Nested{Amount: 456}, + input: &examplepb.UpdateV2Request{ + Abe: &examplepb.ABitOfEverything{ + StringValue: "some updated value because the fieldMask is nil", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Amount: 456, + }, + }, + UpdateMask: &fieldmaskpb.FieldMask{}, + }, + want: &examplepb.ABitOfEverything{ + StringValue: "some updated value because the fieldMask is nil", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Amount: 456, + }, }, }, { // N.B. This case passes the nil field mask to the UpdateV2 method so falls back to PUT semantics as per the implementation. name: "with nil fieldmask", - originalValue: examplepb.ABitOfEverything{ - Int32Value: 42, - StringValue: "some value that will get overwritten", - SingleNested: &examplepb.ABitOfEverything_Nested{Name: "value that will get empty", Amount: 123}, + originalValue: &examplepb.ABitOfEverything{ + Int32Value: 42, + StringValue: "some value that will get overwritten", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Name: "value that will get empty", + Amount: 123, + }, }, - input: examplepb.UpdateV2Request{Abe: &examplepb.ABitOfEverything{ - StringValue: "some updated value because the fieldMask is nil", - SingleNested: &examplepb.ABitOfEverything_Nested{Amount: 657}, - }, UpdateMask: nil}, - want: examplepb.ABitOfEverything{ - StringValue: "some updated value because the fieldMask is nil", - SingleNested: &examplepb.ABitOfEverything_Nested{Amount: 657}, + input: &examplepb.UpdateV2Request{ + Abe: &examplepb.ABitOfEverything{ + StringValue: "some updated value because the fieldMask is nil", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Amount: 657, + }, + }, + UpdateMask: nil, + }, + want: &examplepb.ABitOfEverything{ + StringValue: "some updated value because the fieldMask is nil", + SingleNested: &examplepb.ABitOfEverything_Nested{ + Amount: 657, + }, }, }, } { @@ -825,7 +863,7 @@ func TestABEPatchBody(t *testing.T) { // mustMarshal marshals the given object into a json string, calling t.Fatal if an error occurs. Useful in testing to // inline marshalling whenever you don't expect the marshalling to return an error func mustMarshal(t *testing.T, i interface{}) string { - b, err := json.Marshal(i) + b, err := marshaler.Marshal(i) if err != nil { t.Fatalf("failed to marshal %#v: %v", i, err) } @@ -834,7 +872,7 @@ func mustMarshal(t *testing.T, i interface{}) string { } // postABE conveniently creates a new ABE record for ease in testing -func postABE(t *testing.T, port int, abe examplepb.ABitOfEverything) (uuid string) { +func postABE(t *testing.T, port int, abe *examplepb.ABitOfEverything) (uuid string) { apiURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) postResp, err := http.Post(apiURL, "application/json", strings.NewReader(mustMarshal(t, abe))) if err != nil { @@ -848,7 +886,7 @@ func postABE(t *testing.T, port int, abe examplepb.ABitOfEverything) (uuid strin var f struct { UUID string `json:"uuid"` } - if err := json.Unmarshal(body, &f); err != nil { + if err := marshaler.Unmarshal(body, &f); err != nil { t.Fatalf("postResp body couldn't be unmarshalled: %v. body: %s", err, string(body)) } if f.UUID == "" { @@ -858,7 +896,7 @@ func postABE(t *testing.T, port int, abe examplepb.ABitOfEverything) (uuid strin } // getABE conveniently fetches an ABE record for ease in testing -func getABE(t *testing.T, port int, uuid string) examplepb.ABitOfEverything { +func getABE(t *testing.T, port int, uuid string) *examplepb.ABitOfEverything { gURL := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/%s", port, uuid) getResp, err := http.Get(gURL) if err != nil { @@ -869,16 +907,16 @@ func getABE(t *testing.T, port int, uuid string) examplepb.ABitOfEverything { if got, want := getResp.StatusCode, http.StatusOK; got != want { t.Fatalf("getResp.StatusCode= %d, want %d. resp: %v", got, want, getResp) } - var getRespBody examplepb.ABitOfEverything + var getRestatuspbody examplepb.ABitOfEverything body, err := ioutil.ReadAll(getResp.Body) if err != nil { t.Fatalf("getResp body couldn't be read: %v", err) } - if err := json.Unmarshal(body, &getRespBody); err != nil { + if err := marshaler.Unmarshal(body, &getRestatuspbody); err != nil { t.Fatalf("getResp body couldn't be unmarshalled: %v body: %s", err, string(body)) } - return getRespBody + return &getRestatuspbody } func testABELookupNotFound(t *testing.T, port int) { @@ -904,9 +942,9 @@ func testABELookupNotFound(t *testing.T, port int) { return } - var msg spb.Status - if err := json.Unmarshal(buf, &msg); err != nil { - t.Errorf("json.Unmarshal(%s, &msg) failed with %v; want success", buf, err) + var msg statuspb.Status + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } @@ -940,7 +978,7 @@ func testABEList(t *testing.T, port int) { } defer resp.Body.Close() - dec := json.NewDecoder(resp.Body) + dec := marshaler.NewDecoder(resp.Body) var i int for i = 0; ; i++ { var item struct { @@ -959,8 +997,8 @@ func testABEList(t *testing.T, port int) { continue } var msg examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(item.Result), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", item.Result, err) + if err := marshaler.Unmarshal(item.Result, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", item.Result, err) } } if i <= 0 { @@ -1015,16 +1053,16 @@ func testABEBulkEcho(t *testing.T, port int) { go func() { defer wg.Done() defer reqw.Close() - var m jsonpb.Marshaler for i := 0; i < 1000; i++ { - msg := sub.StringMessage{Value: proto.String(fmt.Sprintf("message %d", i))} - buf, err := m.MarshalToString(&msg) + s := fmt.Sprintf("message %d", i) + msg := sub.StringMessage{Value: &s} + buf, err := marshaler.Marshal(&msg) if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", &msg, err) + t.Errorf("marshaler.Marshal(%v) failed with %v; want success", &msg, err) return } - if _, err := fmt.Fprintln(reqw, buf); err != nil { - t.Errorf("fmt.Fprintln(reqw, %q) failed with %v; want success", buf, err) + if _, err = reqw.Write(buf); err != nil { + t.Errorf("reqw.Write(%q) failed with %v; want success", string(buf), err) return } want = append(want, &msg) @@ -1054,7 +1092,7 @@ func testABEBulkEcho(t *testing.T, port int) { go func() { defer wg.Done() - dec := json.NewDecoder(resp.Body) + dec := marshaler.NewDecoder(resp.Body) for i := 0; ; i++ { var item struct { Result json.RawMessage `json:"result"` @@ -1072,8 +1110,8 @@ func testABEBulkEcho(t *testing.T, port int) { continue } var msg sub.StringMessage - if err := jsonpb.UnmarshalString(string(item.Result), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%q, &msg) failed with %v; want success", item.Result, err) + if err := marshaler.Unmarshal(item.Result, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%q, &msg) failed with %v; want success", item.Result, err) } got = append(got, &msg) } @@ -1104,7 +1142,7 @@ func testABEBulkEchoZeroLength(t *testing.T, port int) { t.Errorf("resp.StatusCode = %d; want %d", got, want) } - dec := json.NewDecoder(resp.Body) + dec := marshaler.NewDecoder(resp.Body) var item struct { Result json.RawMessage `json:"result"` Error map[string]interface{} `json:"error"` @@ -1178,8 +1216,8 @@ func testAdditionalBindings(t *testing.T, port int) { } var msg sub.StringMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success; %d", buf, err, i) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success; %d", buf, err, i) return } if got, want := msg.GetValue(), "hello"; got != want { @@ -1298,8 +1336,8 @@ func testABERepeated(t *testing.T, port int) { } var msg examplepb.ABitOfEverythingRepeated - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) + if err := marshaler.Unmarshal(buf, &msg); err != nil { + t.Errorf("marshaler.Unmarshal(%s, &msg) failed with %v; want success", buf, err) return } if diff := cmp.Diff(msg, want, protocmp.Transform()); diff != "" { @@ -1552,8 +1590,19 @@ func testResponseBodies(t *testing.T, port int) { t.Logf("%s", buf) } - if got, want := string(buf), `[{"data":"foo"}]`; got != want { - t.Errorf("response = %q; want %q", got, want) + var got []*examplepb.ResponseBodyOut_Response + err = marshaler.Unmarshal(buf, &got) + if err != nil { + t.Errorf("marshaler.Unmarshal failed with %v; want success", err) + return + } + want := []*examplepb.ResponseBodyOut_Response{ + { + Data: "foo", + }, + } + if diff := cmp.Diff(got, want, protocmp.Transform()); diff != "" { + t.Errorf(diff) } } @@ -1565,7 +1614,11 @@ func testResponseStrings(t *testing.T, port int) { // Run Secondary server with different marshalling ch := make(chan error) go func() { - if err := runGateway(ctx, fmt.Sprintf(":%d", port), runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{EnumsAsInts: false, EmitDefaults: true})); err != nil { + err := runGateway( + ctx, + fmt.Sprintf(":%d", port), + ) + if err != nil { ch <- fmt.Errorf("cannot run gateway service: %v", err) } }() @@ -1574,51 +1627,102 @@ func testResponseStrings(t *testing.T, port int) { t.Fatalf("waitForGateway(ctx, %d) failed with %v; want success", port, err) } - for i, spec := range []struct { - endpoint string - expectedCode int - expectedBody string - }{ - { - endpoint: fmt.Sprintf("http://localhost:%d/responsestrings/foo", port), - expectedCode: http.StatusOK, - expectedBody: `["hello","foo"]`, - }, - { - endpoint: fmt.Sprintf("http://localhost:%d/responsestrings/empty", port), - expectedCode: http.StatusOK, - expectedBody: `[]`, - }, - { - endpoint: fmt.Sprintf("http://localhost:%d/responsebodies/foo", port), - expectedCode: http.StatusOK, - expectedBody: `[{"data":"foo","type":"UNKNOWN"}]`, - }, - } { - t.Run(strconv.Itoa(i), func(t *testing.T) { - apiURL := spec.endpoint - resp, err := http.Get(apiURL) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) - return - } + t.Run("Response strings", func(t *testing.T) { + apiURL := fmt.Sprintf("http://localhost:%d/responsestrings/foo", port) + resp, err := http.Get(apiURL) + if err != nil { + t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) + return + } + defer resp.Body.Close() + buf, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) + return + } - if got, want := resp.StatusCode, spec.expectedCode; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } + if got, want := resp.StatusCode, http.StatusOK; got != want { + t.Errorf("resp.StatusCode = %d; want %d", got, want) + t.Logf("%s", buf) + } - if got, want := string(buf), spec.expectedBody; got != want { - t.Errorf("response = %q; want %q", got, want) - } - }) - } + var got []string + err = marshaler.Unmarshal(buf, &got) + if err != nil { + t.Errorf("marshaler.Unmarshal failed with %v; want success", err) + return + } + want := []string{"hello", "foo"} + if diff := cmp.Diff(got, want); diff != "" { + t.Errorf(diff) + } + }) + + t.Run("Empty response strings", func(t *testing.T) { + apiURL := fmt.Sprintf("http://localhost:%d/responsestrings/empty", port) + resp, err := http.Get(apiURL) + if err != nil { + t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) + return + } + defer resp.Body.Close() + buf, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) + return + } + + if got, want := resp.StatusCode, http.StatusOK; got != want { + t.Errorf("resp.StatusCode = %d; want %d", got, want) + t.Logf("%s", buf) + } + + var got []string + err = marshaler.Unmarshal(buf, &got) + if err != nil { + t.Errorf("marshaler.Unmarshal failed with %v; want success", err) + return + } + var want []string + if diff := cmp.Diff(got, want); diff != "" { + t.Errorf(diff) + } + }) + + t.Run("Response bodies", func(t *testing.T) { + apiURL := fmt.Sprintf("http://localhost:%d/responsebodies/foo", port) + resp, err := http.Get(apiURL) + if err != nil { + t.Errorf("http.Get(%q) failed with %v; want success", apiURL, err) + return + } + defer resp.Body.Close() + buf, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) + return + } + + if got, want := resp.StatusCode, http.StatusOK; got != want { + t.Errorf("resp.StatusCode = %d; want %d", got, want) + t.Logf("%s", buf) + } + + var got []*examplepb.ResponseBodyOut_Response + err = marshaler.Unmarshal(buf, &got) + if err != nil { + t.Errorf("marshaler.Unmarshal failed with %v; want success", err) + return + } + want := []*examplepb.ResponseBodyOut_Response{ + { + Data: "foo", + }, + } + if diff := cmp.Diff(got, want, protocmp.Transform()); diff != "" { + t.Errorf(diff) + } + }) } @@ -1646,7 +1750,7 @@ func testRequestQueryParams(t *testing.T, port int) { httpMethod string contentType string apiURL string - wantContent string + wantContent *examplepb.ABitOfEverything requestContent io.Reader }{ { @@ -1654,30 +1758,56 @@ func testRequestQueryParams(t *testing.T, port int) { httpMethod: "GET", contentType: "application/json", apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/foo?double_value=%v&bool_value=%v", port, 1234.56, true), - wantContent: `{"single_nested":{"name":"foo"},"double_value":1234.56,"bool_value":true}`, + wantContent: &examplepb.ABitOfEverything{ + SingleNested: &examplepb.ABitOfEverything_Nested{ + Name: "foo", + }, + DoubleValue: 1234.56, + BoolValue: true, + }, }, { name: "get nested enum url parameter", httpMethod: "GET", contentType: "application/json", // If nested_enum.OK were FALSE, the content of single_nested would be {} due to how 0 values are serialized - apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/nested_enum/TRUE", port), - wantContent: `{"single_nested":{"ok":"TRUE"}}`, + apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/nested_enum/TRUE", port), + wantContent: &examplepb.ABitOfEverything{ + SingleNested: &examplepb.ABitOfEverything_Nested{ + Ok: examplepb.ABitOfEverything_Nested_TRUE, + }, + }, }, { - name: "post url query values", - httpMethod: "POST", - contentType: "application/json", - apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/post/hello-world?double_value=%v&bool_value=%v", port, 1234.56, true), - wantContent: `{"single_nested":{"name":"foo","amount":100},"double_value":1234.56,"bool_value":true,"string_value":"hello-world"}`, + name: "post url query values", + httpMethod: "POST", + contentType: "application/json", + apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/post/hello-world?double_value=%v&bool_value=%v", port, 1234.56, true), + wantContent: &examplepb.ABitOfEverything{ + SingleNested: &examplepb.ABitOfEverything_Nested{ + Name: "foo", + Amount: 100, + }, + DoubleValue: 1234.56, + BoolValue: true, + StringValue: "hello-world", + }, requestContent: strings.NewReader(`{"name":"foo","amount":100}`), }, { - name: "post form and url query values", - httpMethod: "POST", - contentType: "application/x-www-form-urlencoded", - apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/foo?double_value=%v&bool_value=%v", port, 1234.56, true), - wantContent: `{"single_nested":{"name":"foo"},"double_value":1234.56,"bool_value":true,"string_value":"hello-world","repeated_string_value":["demo1","demo2"]}`, + name: "post form and url query values", + httpMethod: "POST", + contentType: "application/x-www-form-urlencoded", + apiURL: fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/params/get/foo?double_value=%v&bool_value=%v", port, 1234.56, true), + wantContent: &examplepb.ABitOfEverything{ + SingleNested: &examplepb.ABitOfEverything_Nested{ + Name: "foo", + }, + DoubleValue: 1234.56, + BoolValue: true, + StringValue: "hello-world", + RepeatedStringValue: []string{"demo1", "demo2"}, + }, requestContent: strings.NewReader(formValues.Encode()), }, } @@ -1710,9 +1840,14 @@ func testRequestQueryParams(t *testing.T, port int) { t.Logf("%s", buf) } - gotContent := string(buf) - if gotContent != tc.wantContent { - t.Errorf("http.method (%q) http.url (%q) response = %q; want %q", tc.httpMethod, tc.apiURL, gotContent, tc.wantContent) + var got examplepb.ABitOfEverything + err = marshaler.Unmarshal(buf, &got) + if err != nil { + t.Errorf("marshaler.Unmarshal(buf, got) failed with %v; want success", err) + return + } + if diff := cmp.Diff(got, tc.wantContent, protocmp.Transform()); diff != "" { + t.Errorf("http.method (%q) http.url (%q)\n%s", tc.httpMethod, tc.apiURL, diff) } }) } @@ -1729,21 +1864,29 @@ func TestNonStandardNames(t *testing.T) { defer cancel() go func() { - if err := runGateway( + marshaler := &runtime.JSONPb{ + MarshalOptions: protojson.MarshalOptions{ + UseEnumNumbers: false, + EmitUnpopulated: true, + UseProtoNames: true, + }, + } + err := runGateway( ctx, ":8081", - runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}), - ); err != nil { + runtime.WithMarshalerOption(runtime.MIMEWildcard, marshaler), + ) + if err != nil { t.Errorf("runGateway() failed with %v; want success", err) return } }() go func() { - if err := runGateway( + err := runGateway( ctx, ":8082", - runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: false, EmitDefaults: true}), - ); err != nil { + ) + if err != nil { t.Errorf("runGateway() failed with %v; want success", err) return } @@ -1772,20 +1915,20 @@ func TestNonStandardNames(t *testing.T) { "Test update method using json_names in message", 8081, "update_with_json_names", - // N.B. json_names have no effect if not using OrigName: false + // N.B. json_names have no effect if not using UseProtoNames: false `{"id":"foo","Num":"1","line_num":"42","langIdent":"English","STATUS":"good","en_GB":"1","no":"yes","thing":{"subThing":{"sub_value":"hi"}}}`, }, { - "Test standard update method with OrigName: false marshaller option", + "Test standard update method with UseProtoNames: false marshaller option", 8082, "update", `{"id":"foo","Num":"1","lineNum":"42","langIdent":"English","STATUS":"good","enGB":"1","no":"yes","thing":{"subThing":{"subValue":"hi"}}}`, }, { - "Test update method using json_names in message with OrigName: false marshaller option", + "Test update method using json_names in message with UseProtoNames: false marshaller option", 8082, "update_with_json_names", - `{"ID":"foo","Num":"1","LineNum":"42","langIdent":"English","status":"good","En_GB":"1","yes":"no","Thingy":{"SubThing":{"sub_Value":"hi"}}}`, + `{"ID":"foo","Num":"1","LineNum":"42","langIdent":"English","status":"good","En_GB":"1","yes":"yes","Thingy":{"SubThing":{"sub_Value":"hi"}}}`, }, } { t.Run(tc.name, func(t *testing.T) { @@ -1817,7 +1960,26 @@ func testNonStandardNames(t *testing.T, port int, method string, jsonBody string t.Errorf("patchResp.StatusCode= %d; want %d resp: %v", got, want, string(body)) } - if got, want := string(body), jsonBody; got != want { - t.Errorf("got %q; want %q", got, want) + var got examplepb.NonStandardMessage + err = marshaler.Unmarshal(body, &got) + if err != nil { + t.Errorf("marshler.Unmarshal failed: %v", err) + } + want := &examplepb.NonStandardMessage{ + Id: "foo", + Num: 1, + LineNum: 42, + LangIdent: "English", + STATUS: "good", + En_GB: 1, + No: "yes", + Thing: &examplepb.NonStandardMessage_Thing{ + SubThing: &examplepb.NonStandardMessage_Thing_SubThing{ + SubValue: "hi", + }, + }, + } + if diff := cmp.Diff(got, want, protocmp.Transform()); diff != "" { + t.Errorf(diff) } } diff --git a/examples/internal/proto/examplepb/BUILD.bazel b/examples/internal/proto/examplepb/BUILD.bazel index af7c9b5563d..d00c5a6b00b 100644 --- a/examples/internal/proto/examplepb/BUILD.bazel +++ b/examples/internal/proto/examplepb/BUILD.bazel @@ -69,6 +69,7 @@ go_proto_library( "@com_github_golang_protobuf//descriptor:go_default_library_gen", # keep "@go_googleapis//google/api:annotations_go_proto", "@go_googleapis//google/api:httpbody_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", # keep ], ) @@ -80,11 +81,11 @@ go_library( deps = [ "//internal/utilities:go_default_library", "//runtime:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/examples/internal/proto/examplepb/a_bit_of_everything.pb.gw.go b/examples/internal/proto/examplepb/a_bit_of_everything.pb.gw.go index b06f5ca1436..5ae6bf8d50f 100644 --- a/examples/internal/proto/examplepb/a_bit_of_everything.pb.gw.go +++ b/examples/internal/proto/examplepb/a_bit_of_everything.pb.gw.go @@ -13,7 +13,6 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/pathenum" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/sub" @@ -24,6 +23,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/echo_service.pb.gw.go b/examples/internal/proto/examplepb/echo_service.pb.gw.go index 1d6c0d60b73..2daf2758222 100644 --- a/examples/internal/proto/examplepb/echo_service.pb.gw.go +++ b/examples/internal/proto/examplepb/echo_service.pb.gw.go @@ -13,13 +13,13 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/flow_combination.pb.gw.go b/examples/internal/proto/examplepb/flow_combination.pb.gw.go index 02d57599993..60990f4eb13 100644 --- a/examples/internal/proto/examplepb/flow_combination.pb.gw.go +++ b/examples/internal/proto/examplepb/flow_combination.pb.gw.go @@ -13,13 +13,13 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/non_standard_names.pb.gw.go b/examples/internal/proto/examplepb/non_standard_names.pb.gw.go index 3ce536fcd1d..c8448db166d 100644 --- a/examples/internal/proto/examplepb/non_standard_names.pb.gw.go +++ b/examples/internal/proto/examplepb/non_standard_names.pb.gw.go @@ -13,13 +13,13 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/response_body_service.pb.gw.go b/examples/internal/proto/examplepb/response_body_service.pb.gw.go index 3b0cc5b5865..67dfcc17bbd 100644 --- a/examples/internal/proto/examplepb/response_body_service.pb.gw.go +++ b/examples/internal/proto/examplepb/response_body_service.pb.gw.go @@ -13,13 +13,13 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/stream.pb.gw.go b/examples/internal/proto/examplepb/stream.pb.gw.go index 92508fd4079..a3199f8381e 100644 --- a/examples/internal/proto/examplepb/stream.pb.gw.go +++ b/examples/internal/proto/examplepb/stream.pb.gw.go @@ -13,7 +13,6 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/sub" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" @@ -22,6 +21,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/unannotated_echo_service.pb.gw.go b/examples/internal/proto/examplepb/unannotated_echo_service.pb.gw.go index be8578ed017..a2bb5c2dbcf 100644 --- a/examples/internal/proto/examplepb/unannotated_echo_service.pb.gw.go +++ b/examples/internal/proto/examplepb/unannotated_echo_service.pb.gw.go @@ -13,13 +13,13 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/use_go_template.pb.gw.go b/examples/internal/proto/examplepb/use_go_template.pb.gw.go index 8995be6c988..985d3dee723 100644 --- a/examples/internal/proto/examplepb/use_go_template.pb.gw.go +++ b/examples/internal/proto/examplepb/use_go_template.pb.gw.go @@ -13,13 +13,13 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/examplepb/wrappers.pb.gw.go b/examples/internal/proto/examplepb/wrappers.pb.gw.go index 21d3ad6f54c..3401420c968 100644 --- a/examples/internal/proto/examplepb/wrappers.pb.gw.go +++ b/examples/internal/proto/examplepb/wrappers.pb.gw.go @@ -13,7 +13,6 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/empty" "github.com/golang/protobuf/ptypes/wrappers" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" @@ -22,6 +21,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/proto/standalone/BUILD.bazel b/examples/internal/proto/standalone/BUILD.bazel index ec276799864..1c51d056d96 100644 --- a/examples/internal/proto/standalone/BUILD.bazel +++ b/examples/internal/proto/standalone/BUILD.bazel @@ -9,10 +9,10 @@ go_library( "//examples/internal/proto/examplepb:go_default_library", "//internal/utilities:go_default_library", "//runtime:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/examples/internal/proto/standalone/unannotated_echo_service.pb.gw.go b/examples/internal/proto/standalone/unannotated_echo_service.pb.gw.go index 32e255495dd..afcd2be1732 100644 --- a/examples/internal/proto/standalone/unannotated_echo_service.pb.gw.go +++ b/examples/internal/proto/standalone/unannotated_echo_service.pb.gw.go @@ -13,7 +13,6 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" extExamplepb "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/examplepb" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -21,6 +20,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors diff --git a/examples/internal/server/BUILD.bazel b/examples/internal/server/BUILD.bazel index 89c23e9ee5f..d86eceb7ca6 100644 --- a/examples/internal/server/BUILD.bazel +++ b/examples/internal/server/BUILD.bazel @@ -23,7 +23,6 @@ go_library( "//internal/casing:go_default_library", "//runtime:go_default_library", "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@com_github_rogpeppe_fastuuid//:go_default_library", "@go_googleapis//google/api:httpbody_go_proto", "@go_googleapis//google/rpc:errdetails_go_proto", diff --git a/examples/internal/server/a_bit_of_everything.go b/examples/internal/server/a_bit_of_everything.go index 3c74901a5e4..248d64801b8 100644 --- a/examples/internal/server/a_bit_of_everything.go +++ b/examples/internal/server/a_bit_of_everything.go @@ -8,10 +8,9 @@ import ( "time" "github.com/golang/glog" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/wrappers" + durationpb "github.com/golang/protobuf/ptypes/duration" + emptypb "github.com/golang/protobuf/ptypes/empty" + wrapperspb "github.com/golang/protobuf/ptypes/wrappers" examples "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/examplepb" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/sub" "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/sub2" @@ -102,7 +101,7 @@ func (s *_ABitOfEverythingServer) BulkCreate(stream examples.StreamService_BulkC "foo": "foo2", "bar": "bar2", })) - return stream.SendAndClose(new(empty.Empty)) + return stream.SendAndClose(new(emptypb.Empty)) } func (s *_ABitOfEverythingServer) Lookup(ctx context.Context, msg *sub2.IdMessage) (*examples.ABitOfEverything, error) { @@ -128,7 +127,7 @@ func (s *_ABitOfEverythingServer) Lookup(ctx context.Context, msg *sub2.IdMessag return nil, status.Errorf(codes.NotFound, "not found") } -func (s *_ABitOfEverythingServer) List(_ *empty.Empty, stream examples.StreamService_ListServer) error { +func (s *_ABitOfEverythingServer) List(_ *emptypb.Empty, stream examples.StreamService_ListServer) error { s.m.Lock() defer s.m.Unlock() @@ -158,7 +157,7 @@ func (s *_ABitOfEverythingServer) List(_ *empty.Empty, stream examples.StreamSer return nil } -func (s *_ABitOfEverythingServer) Download(_ *empty.Empty, stream examples.StreamService_DownloadServer) error { +func (s *_ABitOfEverythingServer) Download(_ *emptypb.Empty, stream examples.StreamService_DownloadServer) error { msgs := []*httpbody.HttpBody{{ ContentType: "text/html", Data: []byte("Hello 1"), @@ -178,7 +177,7 @@ func (s *_ABitOfEverythingServer) Download(_ *empty.Empty, stream examples.Strea return nil } -func (s *_ABitOfEverythingServer) Update(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) { +func (s *_ABitOfEverythingServer) Update(ctx context.Context, msg *examples.ABitOfEverything) (*emptypb.Empty, error) { s.m.Lock() defer s.m.Unlock() @@ -188,10 +187,10 @@ func (s *_ABitOfEverythingServer) Update(ctx context.Context, msg *examples.ABit } else { return nil, status.Errorf(codes.NotFound, "not found") } - return new(empty.Empty), nil + return new(emptypb.Empty), nil } -func (s *_ABitOfEverythingServer) UpdateV2(ctx context.Context, msg *examples.UpdateV2Request) (*empty.Empty, error) { +func (s *_ABitOfEverythingServer) UpdateV2(ctx context.Context, msg *examples.UpdateV2Request) (*emptypb.Empty, error) { glog.Info(msg) // If there is no update mask do a regular update if msg.UpdateMask == nil || len(msg.UpdateMask.GetPaths()) == 0 { @@ -205,10 +204,10 @@ func (s *_ABitOfEverythingServer) UpdateV2(ctx context.Context, msg *examples.Up } else { return nil, status.Errorf(codes.NotFound, "not found") } - return new(empty.Empty), nil + return new(emptypb.Empty), nil } -func (s *_ABitOfEverythingServer) Delete(ctx context.Context, msg *sub2.IdMessage) (*empty.Empty, error) { +func (s *_ABitOfEverythingServer) Delete(ctx context.Context, msg *sub2.IdMessage) (*emptypb.Empty, error) { s.m.Lock() defer s.m.Unlock() @@ -218,10 +217,10 @@ func (s *_ABitOfEverythingServer) Delete(ctx context.Context, msg *sub2.IdMessag } else { return nil, status.Errorf(codes.NotFound, "not found") } - return new(empty.Empty), nil + return new(emptypb.Empty), nil } -func (s *_ABitOfEverythingServer) GetQuery(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) { +func (s *_ABitOfEverythingServer) GetQuery(ctx context.Context, msg *examples.ABitOfEverything) (*emptypb.Empty, error) { s.m.Lock() defer s.m.Unlock() @@ -231,7 +230,7 @@ func (s *_ABitOfEverythingServer) GetQuery(ctx context.Context, msg *examples.AB } else { return nil, status.Errorf(codes.NotFound, "not found") } - return new(empty.Empty), nil + return new(emptypb.Empty), nil } func (s *_ABitOfEverythingServer) GetRepeatedQuery(ctx context.Context, msg *examples.ABitOfEverythingRepeated) (*examples.ABitOfEverythingRepeated, error) { @@ -293,37 +292,35 @@ func (s *_ABitOfEverythingServer) DeepPathEcho(ctx context.Context, msg *example return msg, nil } -func (s *_ABitOfEverythingServer) NoBindings(ctx context.Context, msg *duration.Duration) (*empty.Empty, error) { +func (s *_ABitOfEverythingServer) NoBindings(ctx context.Context, msg *durationpb.Duration) (*emptypb.Empty, error) { return nil, nil } -func (s *_ABitOfEverythingServer) Timeout(ctx context.Context, msg *empty.Empty) (*empty.Empty, error) { +func (s *_ABitOfEverythingServer) Timeout(ctx context.Context, msg *emptypb.Empty) (*emptypb.Empty, error) { select { case <-ctx.Done(): return nil, ctx.Err() } } -func (s *_ABitOfEverythingServer) ErrorWithDetails(ctx context.Context, msg *empty.Empty) (*empty.Empty, error) { +func (s *_ABitOfEverythingServer) ErrorWithDetails(ctx context.Context, msg *emptypb.Empty) (*emptypb.Empty, error) { stat, err := status.New(codes.Unknown, "with details"). - WithDetails(proto.Message( - &errdetails.DebugInfo{ - StackEntries: []string{"foo:1"}, - Detail: "error debug details", - }, - )) + WithDetails(&errdetails.DebugInfo{ + StackEntries: []string{"foo:1"}, + Detail: "error debug details", + }) if err != nil { return nil, status.Errorf(codes.Internal, "unexpected error adding details: %s", err) } return nil, stat.Err() } -func (s *_ABitOfEverythingServer) GetMessageWithBody(ctx context.Context, msg *examples.MessageWithBody) (*empty.Empty, error) { - return &empty.Empty{}, nil +func (s *_ABitOfEverythingServer) GetMessageWithBody(ctx context.Context, msg *examples.MessageWithBody) (*emptypb.Empty, error) { + return &emptypb.Empty{}, nil } -func (s *_ABitOfEverythingServer) PostWithEmptyBody(ctx context.Context, msg *examples.Body) (*empty.Empty, error) { - return &empty.Empty{}, nil +func (s *_ABitOfEverythingServer) PostWithEmptyBody(ctx context.Context, msg *examples.Body) (*emptypb.Empty, error) { + return &emptypb.Empty{}, nil } func (s *_ABitOfEverythingServer) CheckGetQueryParams(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { @@ -338,6 +335,6 @@ func (s *_ABitOfEverythingServer) CheckPostQueryParams(ctx context.Context, msg return msg, nil } -func (s *_ABitOfEverythingServer) OverwriteResponseContentType(ctx context.Context, msg *empty.Empty) (*wrappers.StringValue, error) { - return &wrappers.StringValue{}, nil +func (s *_ABitOfEverythingServer) OverwriteResponseContentType(ctx context.Context, msg *emptypb.Empty) (*wrapperspb.StringValue, error) { + return &wrapperspb.StringValue{}, nil } diff --git a/internal/codegenerator/BUILD.bazel b/internal/codegenerator/BUILD.bazel index 9d0aa3741f1..a87434f4a5d 100644 --- a/internal/codegenerator/BUILD.bazel +++ b/internal/codegenerator/BUILD.bazel @@ -10,8 +10,8 @@ go_library( ], importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/internal/codegenerator", deps = [ - "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", ], ) @@ -20,9 +20,9 @@ go_test( srcs = ["parse_req_test.go"], embed = [":go_default_library"], deps = [ - "@com_github_golang_protobuf//proto:go_default_library", "@com_github_google_go_cmp//cmp:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", "@org_golang_google_protobuf//testing/protocmp:go_default_library", ], ) diff --git a/internal/codegenerator/parse_req.go b/internal/codegenerator/parse_req.go index e74575bddcd..dd489f005a2 100644 --- a/internal/codegenerator/parse_req.go +++ b/internal/codegenerator/parse_req.go @@ -5,17 +5,17 @@ import ( "io" "io/ioutil" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" + "google.golang.org/protobuf/proto" ) // ParseRequest parses a code generator request from a proto Message. -func ParseRequest(r io.Reader) (*plugin.CodeGeneratorRequest, error) { +func ParseRequest(r io.Reader) (*pluginpb.CodeGeneratorRequest, error) { input, err := ioutil.ReadAll(r) if err != nil { return nil, fmt.Errorf("failed to read code generator request: %v", err) } - req := new(plugin.CodeGeneratorRequest) + req := new(pluginpb.CodeGeneratorRequest) if err = proto.Unmarshal(input, req); err != nil { return nil, fmt.Errorf("failed to unmarshal code generator request: %v", err) } diff --git a/internal/codegenerator/parse_req_test.go b/internal/codegenerator/parse_req_test.go index c2eb9e757ed..8decf50aaca 100644 --- a/internal/codegenerator/parse_req_test.go +++ b/internal/codegenerator/parse_req_test.go @@ -8,23 +8,23 @@ import ( "strings" "testing" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/google/go-cmp/cmp" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/codegenerator" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/testing/protocmp" ) var parseReqTests = []struct { name string in io.Reader - out *plugin.CodeGeneratorRequest + out *pluginpb.CodeGeneratorRequest err error }{ { "Empty input should produce empty output", - mustGetReader(&plugin.CodeGeneratorRequest{}), - &plugin.CodeGeneratorRequest{}, + mustGetReader(&pluginpb.CodeGeneratorRequest{}), + &pluginpb.CodeGeneratorRequest{}, nil, }, { diff --git a/internal/descriptor/BUILD.bazel b/internal/descriptor/BUILD.bazel index 326847be68a..3e74322d63a 100644 --- a/internal/descriptor/BUILD.bazel +++ b/internal/descriptor/BUILD.bazel @@ -17,11 +17,11 @@ go_library( "//internal/httprule:go_default_library", "@com_github_ghodss_yaml//:go_default_library", "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library_gen", - "@com_github_golang_protobuf//proto:go_default_library", "@go_googleapis//google/api:annotations_go_proto", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", + "@org_golang_google_protobuf//encoding/protojson:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", ], ) @@ -37,8 +37,9 @@ go_test( embed = [":go_default_library"], deps = [ "//internal/httprule:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", + "@org_golang_google_protobuf//encoding/prototext:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/internal/descriptor/grpc_api_configuration.go b/internal/descriptor/grpc_api_configuration.go index cb112fa5ed3..c3a5ea8003a 100644 --- a/internal/descriptor/grpc_api_configuration.go +++ b/internal/descriptor/grpc_api_configuration.go @@ -1,14 +1,13 @@ package descriptor import ( - "bytes" "fmt" "io/ioutil" "strings" "github.com/ghodss/yaml" - "github.com/golang/protobuf/jsonpb" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor/apiconfig" + "google.golang.org/protobuf/encoding/protojson" ) func loadGrpcAPIServiceFromYAML(yamlFileContents []byte, yamlSourceLogName string) (*apiconfig.GrpcAPIService, error) { @@ -17,13 +16,13 @@ func loadGrpcAPIServiceFromYAML(yamlFileContents []byte, yamlSourceLogName strin return nil, fmt.Errorf("Failed to convert gRPC API Configuration from YAML in '%v' to JSON: %v", yamlSourceLogName, err) } - // As our GrpcAPIService is incomplete accept unkown fields. - unmarshaler := jsonpb.Unmarshaler{ - AllowUnknownFields: true, + // As our GrpcAPIService is incomplete, accept unknown fields. + unmarshaler := protojson.UnmarshalOptions{ + DiscardUnknown: true, } serviceConfiguration := apiconfig.GrpcAPIService{} - if err := unmarshaler.Unmarshal(bytes.NewReader(jsonContents), &serviceConfiguration); err != nil { + if err := unmarshaler.Unmarshal(jsonContents, &serviceConfiguration); err != nil { return nil, fmt.Errorf("Failed to parse gRPC API Configuration from YAML in '%v': %v", yamlSourceLogName, err) } diff --git a/internal/descriptor/grpc_api_configuration_test.go b/internal/descriptor/grpc_api_configuration_test.go index 28448a180c6..e6ac3d10aa3 100644 --- a/internal/descriptor/grpc_api_configuration_test.go +++ b/internal/descriptor/grpc_api_configuration_test.go @@ -5,21 +5,6 @@ import ( "testing" ) -func TestLoadGrpcAPIServiceFromYAMLEmpty(t *testing.T) { - service, err := loadGrpcAPIServiceFromYAML([]byte(``), "empty") - if err != nil { - t.Fatal(err) - } - - if service == nil { - t.Fatal("No service returned") - } - - if service.Http != nil { - t.Fatal("HTTP not empty") - } -} - func TestLoadGrpcAPIServiceFromYAMLInvalidType(t *testing.T) { // Ideally this would fail but for now this test documents that it doesn't service, err := loadGrpcAPIServiceFromYAML([]byte(`type: not.the.right.type`), "invalidtype") diff --git a/internal/descriptor/registry.go b/internal/descriptor/registry.go index 3b343ea8ca2..dcc2db92045 100644 --- a/internal/descriptor/registry.go +++ b/internal/descriptor/registry.go @@ -7,12 +7,12 @@ import ( "strings" "github.com/golang/glog" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" "google.golang.org/genproto/googleapis/api/annotations" ) -// Registry is a registry of information extracted from plugin.CodeGeneratorRequest. +// Registry is a registry of information extracted from pluginpb.CodeGeneratorRequest. type Registry struct { // msgs is a mapping from fully-qualified message name to descriptor msgs map[string]*Message @@ -112,7 +112,7 @@ func NewRegistry() *Registry { } // Load loads definitions of services, methods, messages, enumerations and fields from "req". -func (r *Registry) Load(req *plugin.CodeGeneratorRequest) error { +func (r *Registry) Load(req *pluginpb.CodeGeneratorRequest) error { for _, file := range req.GetProtoFile() { r.loadFile(file) } @@ -142,7 +142,7 @@ func (r *Registry) Load(req *plugin.CodeGeneratorRequest) error { // loadFile loads messages, enumerations and fields from "file". // It does not loads services and methods in "file". You need to call // loadServices after loadFiles is called for all files to load services and methods. -func (r *Registry) loadFile(file *descriptor.FileDescriptorProto) { +func (r *Registry) loadFile(file *descriptorpb.FileDescriptorProto) { pkg := GoPackage{ Path: r.goPackagePath(file), Name: r.defaultGoPackageName(file), @@ -170,7 +170,7 @@ func (r *Registry) loadFile(file *descriptor.FileDescriptorProto) { r.registerEnum(f, nil, file.GetEnumType()) } -func (r *Registry) registerMsg(file *File, outerPath []string, msgs []*descriptor.DescriptorProto) { +func (r *Registry) registerMsg(file *File, outerPath []string, msgs []*descriptorpb.DescriptorProto) { for i, md := range msgs { m := &Message{ File: file, @@ -198,7 +198,7 @@ func (r *Registry) registerMsg(file *File, outerPath []string, msgs []*descripto } } -func (r *Registry) registerEnum(file *File, outerPath []string, enums []*descriptor.EnumDescriptorProto) { +func (r *Registry) registerEnum(file *File, outerPath []string, enums []*descriptorpb.EnumDescriptorProto) { for i, ed := range enums { e := &Enum{ File: file, @@ -347,7 +347,7 @@ func (r *Registry) ReserveGoPackageAlias(alias, pkgpath string) error { // goPackagePath returns the go package path which go files generated from "f" should have. // It respects the mapping registered by AddPkgMap if exists. Or use go_package as import path // if it includes a slash, Otherwide, it generates a path from the file name of "f". -func (r *Registry) goPackagePath(f *descriptor.FileDescriptorProto) string { +func (r *Registry) goPackagePath(f *descriptorpb.FileDescriptorProto) string { name := f.GetName() if pkg, ok := r.pkgMap[name]; ok { return path.Join(r.prefix, pkg) @@ -548,7 +548,7 @@ func sanitizePackageName(pkgName string) string { // defaultGoPackageName returns the default go package name to be used for go files generated from "f". // You might need to use an unique alias for the package when you import it. Use ReserveGoPackageAlias to get a unique alias. -func (r *Registry) defaultGoPackageName(f *descriptor.FileDescriptorProto) string { +func (r *Registry) defaultGoPackageName(f *descriptorpb.FileDescriptorProto) string { name := r.packageIdentityName(f) return sanitizePackageName(name) } @@ -556,7 +556,7 @@ func (r *Registry) defaultGoPackageName(f *descriptor.FileDescriptorProto) strin // packageIdentityName returns the identity of packages. // protoc-gen-grpc-gateway rejects CodeGenerationRequests which contains more than one packages // as protoc-gen-go does. -func (r *Registry) packageIdentityName(f *descriptor.FileDescriptorProto) string { +func (r *Registry) packageIdentityName(f *descriptorpb.FileDescriptorProto) string { if f.Options != nil && f.Options.GoPackage != nil { gopkg := f.Options.GetGoPackage() idx := strings.LastIndex(gopkg, "/") diff --git a/internal/descriptor/registry_test.go b/internal/descriptor/registry_test.go index 1ec72a8cacd..59f05793e6a 100644 --- a/internal/descriptor/registry_test.go +++ b/internal/descriptor/registry_test.go @@ -3,14 +3,14 @@ package descriptor import ( "testing" - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" + "google.golang.org/protobuf/encoding/prototext" ) -func loadFile(t *testing.T, reg *Registry, src string) *descriptor.FileDescriptorProto { - var file descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &file); err != nil { +func loadFile(t *testing.T, reg *Registry, src string) *descriptorpb.FileDescriptorProto { + var file descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &file); err != nil { t.Fatalf("proto.UnmarshalText(%s, &file) failed with %v; want success", src, err) } reg.loadFile(&file) @@ -18,8 +18,8 @@ func loadFile(t *testing.T, reg *Registry, src string) *descriptor.FileDescripto } func load(t *testing.T, reg *Registry, src string) error { - var req plugin.CodeGeneratorRequest - if err := proto.UnmarshalText(src, &req); err != nil { + var req pluginpb.CodeGeneratorRequest + if err := prototext.Unmarshal([]byte(src), &req); err != nil { t.Fatalf("proto.UnmarshalText(%s, &file) failed with %v; want success", src, err) } return reg.Load(&req) diff --git a/internal/descriptor/services.go b/internal/descriptor/services.go index b85e6d47922..d2f1e0aaf85 100644 --- a/internal/descriptor/services.go +++ b/internal/descriptor/services.go @@ -5,10 +5,10 @@ import ( "strings" "github.com/golang/glog" - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" options "google.golang.org/genproto/googleapis/api/annotations" + "google.golang.org/protobuf/proto" ) // loadServices registers services and their methods from "targetFile" to "r". @@ -54,7 +54,7 @@ func (r *Registry) loadServices(file *File) error { return nil } -func (r *Registry) newMethod(svc *Service, md *descriptor.MethodDescriptorProto, optsList []*options.HttpRule) (*Method, error) { +func (r *Registry) newMethod(svc *Service, md *descriptorpb.MethodDescriptorProto, optsList []*options.HttpRule) (*Method, error) { requestType, err := r.LookupMsg(svc.File.GetPackage(), md.GetInputType()) if err != nil { return nil, err @@ -184,17 +184,14 @@ func (r *Registry) newMethod(svc *Service, md *descriptor.MethodDescriptorProto, return meth, nil } -func extractAPIOptions(meth *descriptor.MethodDescriptorProto) (*options.HttpRule, error) { +func extractAPIOptions(meth *descriptorpb.MethodDescriptorProto) (*options.HttpRule, error) { if meth.Options == nil { return nil, nil } if !proto.HasExtension(meth.Options, options.E_Http) { return nil, nil } - ext, err := proto.GetExtension(meth.Options, options.E_Http) - if err != nil { - return nil, err - } + ext := proto.GetExtension(meth.Options, options.E_Http) opts, ok := ext.(*options.HttpRule) if !ok { return nil, fmt.Errorf("extension is %T; want an HttpRule", ext) @@ -214,7 +211,7 @@ func (r *Registry) newParam(meth *Method, path string) (Parameter, error) { } target := fields[l-1].Target switch target.GetType() { - case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP: + case descriptorpb.FieldDescriptorProto_TYPE_MESSAGE, descriptorpb.FieldDescriptorProto_TYPE_GROUP: glog.V(2).Infoln("found aggregate type:", target, target.TypeName) if IsWellKnownType(*target.TypeName) { glog.V(2).Infoln("found well known aggregate type:", target) @@ -280,7 +277,7 @@ func (r *Registry) resolveFieldPath(msg *Message, path string, isPathParam bool) if i > 0 { f := result[i-1].Target switch f.GetType() { - case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP: + case descriptorpb.FieldDescriptorProto_TYPE_MESSAGE, descriptorpb.FieldDescriptorProto_TYPE_GROUP: var err error msg, err = r.LookupMsg(msg.FQMN(), f.GetTypeName()) if err != nil { @@ -296,7 +293,7 @@ func (r *Registry) resolveFieldPath(msg *Message, path string, isPathParam bool) if f == nil { return nil, fmt.Errorf("no field %q found in %s", path, root.GetName()) } - if !(isPathParam || r.allowRepeatedFieldsInBody) && f.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED { + if !(isPathParam || r.allowRepeatedFieldsInBody) && f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED { return nil, fmt.Errorf("repeated field not allowed in field path: %s in %s", f.GetName(), path) } result = append(result, FieldPathComponent{Name: c, Target: f}) diff --git a/internal/descriptor/services_test.go b/internal/descriptor/services_test.go index bc984aae966..7b68ac206c4 100644 --- a/internal/descriptor/services_test.go +++ b/internal/descriptor/services_test.go @@ -4,9 +4,10 @@ import ( "reflect" "testing" - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" + "google.golang.org/protobuf/encoding/prototext" + "google.golang.org/protobuf/proto" ) func compilePath(t *testing.T, path string) httprule.Template { @@ -17,7 +18,7 @@ func compilePath(t *testing.T, path string) httprule.Template { return parsed.Compile() } -func testExtractServices(t *testing.T, input []*descriptor.FileDescriptorProto, target string, wantSvcs []*Service) { +func testExtractServices(t *testing.T, input []*descriptorpb.FileDescriptorProto, target string, wantSvcs []*Service) { reg := NewRegistry() for _, file := range input { reg.loadFile(file) @@ -178,8 +179,8 @@ func TestExtractServicesSimple(t *testing.T) { > > ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ @@ -219,7 +220,7 @@ func TestExtractServicesSimple(t *testing.T) { } crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) + testExtractServices(t, []*descriptorpb.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithoutAnnotation(t *testing.T) { @@ -244,8 +245,8 @@ func TestExtractServicesWithoutAnnotation(t *testing.T) { > > ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ @@ -278,7 +279,7 @@ func TestExtractServicesWithoutAnnotation(t *testing.T) { } crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) + testExtractServices(t, []*descriptorpb.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesCrossPackage(t *testing.T) { @@ -323,10 +324,10 @@ func TestExtractServicesCrossPackage(t *testing.T) { > `, } - var fds []*descriptor.FileDescriptorProto + var fds []*descriptorpb.FileDescriptorProto for _, src := range srcs { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } fds = append(fds, &fd) @@ -429,8 +430,8 @@ func TestExtractServicesWithBodyPath(t *testing.T) { > > ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ @@ -477,7 +478,7 @@ func TestExtractServicesWithBodyPath(t *testing.T) { } crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) + testExtractServices(t, []*descriptorpb.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithPathParam(t *testing.T) { @@ -507,8 +508,8 @@ func TestExtractServicesWithPathParam(t *testing.T) { > > ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ @@ -558,7 +559,7 @@ func TestExtractServicesWithPathParam(t *testing.T) { } crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) + testExtractServices(t, []*descriptorpb.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithAdditionalBinding(t *testing.T) { @@ -596,8 +597,8 @@ func TestExtractServicesWithAdditionalBinding(t *testing.T) { > > ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } msg := &Message{ @@ -668,7 +669,7 @@ func TestExtractServicesWithAdditionalBinding(t *testing.T) { } crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) + testExtractServices(t, []*descriptorpb.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) } func TestExtractServicesWithError(t *testing.T) { @@ -967,10 +968,10 @@ func TestExtractServicesWithError(t *testing.T) { } { reg := NewRegistry() - var fds []*descriptor.FileDescriptorProto + var fds []*descriptorpb.FileDescriptorProto for _, src := range spec.srcs { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } reg.loadFile(&fd) @@ -1149,8 +1150,8 @@ func TestResolveFieldPath(t *testing.T) { wantErr: true, }, } { - var file descriptor.FileDescriptorProto - if err := proto.UnmarshalText(spec.src, &file); err != nil { + var file descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(spec.src), &file); err != nil { t.Fatalf("proto.Unmarshal(%s) failed with %v; want success", spec.src, err) } reg := NewRegistry() @@ -1251,10 +1252,10 @@ func TestExtractServicesWithDeleteBody(t *testing.T) { reg := NewRegistry() reg.SetAllowDeleteBody(spec.allowDeleteBody) - var fds []*descriptor.FileDescriptorProto + var fds []*descriptorpb.FileDescriptorProto for _, src := range spec.srcs { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } reg.loadFile(&fd) diff --git a/internal/descriptor/types.go b/internal/descriptor/types.go index 41e8553ed68..b02515a4682 100644 --- a/internal/descriptor/types.go +++ b/internal/descriptor/types.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/golang/protobuf/protoc-gen-go/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/casing" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" ) @@ -38,9 +38,9 @@ func (p GoPackage) String() string { return fmt.Sprintf("%s %q", p.Alias, p.Path) } -// File wraps descriptor.FileDescriptorProto for richer features. +// File wraps descriptorpb.FileDescriptorProto for richer features. type File struct { - *descriptor.FileDescriptorProto + *descriptorpb.FileDescriptorProto // GoPkg is the go package of the go file generated from this file.. GoPkg GoPackage // Messages is the list of messages defined in this file. @@ -71,7 +71,7 @@ type Message struct { File *File // Outers is a list of outer messages if this message is a nested type. Outers []string - *descriptor.DescriptorProto + *descriptorpb.DescriptorProto Fields []*Field // Index is proto path index of this message in File. @@ -112,7 +112,7 @@ type Enum struct { File *File // Outers is a list of outer messages if this enum is a nested type. Outers []string - *descriptor.EnumDescriptorProto + *descriptorpb.EnumDescriptorProto Index int @@ -145,11 +145,11 @@ func (e *Enum) GoType(currentPackage string) string { return fmt.Sprintf("%s.%s", e.File.Pkg(), name) } -// Service wraps descriptor.ServiceDescriptorProto for richer features. +// Service wraps descriptorpb.ServiceDescriptorProto for richer features. type Service struct { // File is the file where this service is defined. File *File - *descriptor.ServiceDescriptorProto + *descriptorpb.ServiceDescriptorProto // Methods is the list of methods defined in this service. Methods []*Method @@ -183,11 +183,11 @@ func (s *Service) ClientConstructorName() string { return fmt.Sprintf("%s.%s", s.File.Pkg(), constructor) } -// Method wraps descriptor.MethodDescriptorProto for richer features. +// Method wraps descriptorpb.MethodDescriptorProto for richer features. type Method struct { // Service is the service which this method belongs to. Service *Service - *descriptor.MethodDescriptorProto + *descriptorpb.MethodDescriptorProto // RequestType is the message type of requests to this method. RequestType *Message @@ -235,13 +235,13 @@ func (b *Binding) ExplicitParams() []string { return result } -// Field wraps descriptor.FieldDescriptorProto for richer features. +// Field wraps descriptorpb.FieldDescriptorProto for richer features. type Field struct { // Message is the message type which this field belongs to. Message *Message // FieldMessage is the message type of the field. FieldMessage *Message - *descriptor.FieldDescriptorProto + *descriptorpb.FieldDescriptorProto ForcePrefixedName bool } @@ -280,12 +280,12 @@ func (p Parameter) ConvertFuncExpr() (string, error) { // IsEnum returns true if the field is an enum type, otherwise false is returned. func (p Parameter) IsEnum() bool { - return p.Target.GetType() == descriptor.FieldDescriptorProto_TYPE_ENUM + return p.Target.GetType() == descriptorpb.FieldDescriptorProto_TYPE_ENUM } // IsRepeated returns true if the field is repeated, otherwise false is returned. func (p Parameter) IsRepeated() bool { - return p.Target.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED + return p.Target.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED } // IsProto2 returns true if the field is proto2, otherwise false is returned. @@ -394,90 +394,90 @@ func (c FieldPathComponent) ValueExpr() string { } var ( - proto3ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ - descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64", - descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32", - descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64", - descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64", - descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32", - descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64", - descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32", - descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.Bool", - descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.String", + proto3ConvertFuncs = map[descriptorpb.FieldDescriptorProto_Type]string{ + descriptorpb.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64", + descriptorpb.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32", + descriptorpb.FieldDescriptorProto_TYPE_INT64: "runtime.Int64", + descriptorpb.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64", + descriptorpb.FieldDescriptorProto_TYPE_INT32: "runtime.Int32", + descriptorpb.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64", + descriptorpb.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32", + descriptorpb.FieldDescriptorProto_TYPE_BOOL: "runtime.Bool", + descriptorpb.FieldDescriptorProto_TYPE_STRING: "runtime.String", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE - descriptor.FieldDescriptorProto_TYPE_BYTES: "runtime.Bytes", - descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32", - descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.Enum", - descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32", - descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64", - descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32", - descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64", + descriptorpb.FieldDescriptorProto_TYPE_BYTES: "runtime.Bytes", + descriptorpb.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32", + descriptorpb.FieldDescriptorProto_TYPE_ENUM: "runtime.Enum", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64", + descriptorpb.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32", + descriptorpb.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64", } - proto3RepeatedConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ - descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice", - descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice", - descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice", - descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice", - descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice", - descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice", - descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice", - descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice", - descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice", + proto3RepeatedConvertFuncs = map[descriptorpb.FieldDescriptorProto_Type]string{ + descriptorpb.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice", + descriptorpb.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice", + descriptorpb.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice", + descriptorpb.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice", + descriptorpb.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice", + descriptorpb.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice", + descriptorpb.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice", + descriptorpb.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice", + descriptorpb.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE - descriptor.FieldDescriptorProto_TYPE_BYTES: "runtime.BytesSlice", - descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice", - descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice", - descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice", - descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice", - descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice", - descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice", + descriptorpb.FieldDescriptorProto_TYPE_BYTES: "runtime.BytesSlice", + descriptorpb.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice", + descriptorpb.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice", + descriptorpb.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice", + descriptorpb.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice", } - proto2ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ - descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64P", - descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32P", - descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64P", - descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64P", - descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32P", - descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64P", - descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32P", - descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolP", - descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringP", + proto2ConvertFuncs = map[descriptorpb.FieldDescriptorProto_Type]string{ + descriptorpb.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64P", + descriptorpb.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32P", + descriptorpb.FieldDescriptorProto_TYPE_INT64: "runtime.Int64P", + descriptorpb.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64P", + descriptorpb.FieldDescriptorProto_TYPE_INT32: "runtime.Int32P", + descriptorpb.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64P", + descriptorpb.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32P", + descriptorpb.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolP", + descriptorpb.FieldDescriptorProto_TYPE_STRING: "runtime.StringP", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE // FieldDescriptorProto_TYPE_BYTES // TODO(yugui) Handle bytes - descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32P", - descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumP", - descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32P", - descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64P", - descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32P", - descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64P", + descriptorpb.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32P", + descriptorpb.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumP", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32P", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64P", + descriptorpb.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32P", + descriptorpb.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64P", } - proto2RepeatedConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ - descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice", - descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice", - descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice", - descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice", - descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice", - descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice", - descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice", - descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice", - descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice", + proto2RepeatedConvertFuncs = map[descriptorpb.FieldDescriptorProto_Type]string{ + descriptorpb.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice", + descriptorpb.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice", + descriptorpb.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice", + descriptorpb.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice", + descriptorpb.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice", + descriptorpb.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice", + descriptorpb.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice", + descriptorpb.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice", + descriptorpb.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice", // FieldDescriptorProto_TYPE_GROUP // FieldDescriptorProto_TYPE_MESSAGE // FieldDescriptorProto_TYPE_BYTES // TODO(maros7) Handle bytes - descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice", - descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice", - descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice", - descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice", - descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice", - descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice", + descriptorpb.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice", + descriptorpb.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice", + descriptorpb.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice", + descriptorpb.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice", + descriptorpb.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice", } wellKnownTypeConv = map[string]string{ diff --git a/internal/descriptor/types_test.go b/internal/descriptor/types_test.go index 9c7046b1e2e..60e5bc0a17e 100644 --- a/internal/descriptor/types_test.go +++ b/internal/descriptor/types_test.go @@ -3,8 +3,8 @@ package descriptor import ( "testing" - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" + "google.golang.org/protobuf/encoding/prototext" ) func TestGoPackageStandard(t *testing.T) { @@ -21,7 +21,7 @@ func TestGoPackageStandard(t *testing.T) { want: true, }, { - pkg: GoPackage{Path: "github.com/golang/protobuf/jsonpb", Name: "jsonpb"}, + pkg: GoPackage{Path: "google.golang.org/protobuf/encoding/protojson", Name: "jsonpb"}, want: false, }, { @@ -57,8 +57,8 @@ func TestGoPackageString(t *testing.T) { want: `"encoding/json"`, }, { - pkg: GoPackage{Path: "github.com/golang/protobuf/jsonpb", Name: "jsonpb"}, - want: `"github.com/golang/protobuf/jsonpb"`, + pkg: GoPackage{Path: "google.golang.org/protobuf/encoding/protojson", Name: "jsonpb"}, + want: `"google.golang.org/protobuf/encoding/protojson"`, }, { pkg: GoPackage{Path: "golang.org/x/net/context", Name: "context"}, @@ -80,7 +80,7 @@ func TestGoPackageString(t *testing.T) { } func TestFieldPath(t *testing.T) { - var fds []*descriptor.FileDescriptorProto + var fds []*descriptorpb.FileDescriptorProto for _, src := range []string{ ` name: 'example.proto' @@ -124,8 +124,8 @@ func TestFieldPath(t *testing.T) { syntax: "proto2" `, } { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } fds = append(fds, &fd) @@ -222,8 +222,8 @@ func TestGoType(t *testing.T) { >, ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { + var fd descriptorpb.FileDescriptorProto + if err := prototext.Unmarshal([]byte(src), &fd); err != nil { t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) } diff --git a/internal/generator/generator.go b/internal/generator/generator.go index 21255eaa95b..88b055bf591 100644 --- a/internal/generator/generator.go +++ b/internal/generator/generator.go @@ -2,12 +2,12 @@ package generator import ( - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" + descriptorpb "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" ) // Generator is an abstraction of code generators. type Generator interface { // Generate generates output files from input .proto files. - Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) + Generate(targets []*descriptorpb.File) ([]*pluginpb.CodeGeneratorResponse_File, error) } diff --git a/protoc-gen-grpc-gateway/BUILD.bazel b/protoc-gen-grpc-gateway/BUILD.bazel index 09851518641..a3d54fe0b9e 100644 --- a/protoc-gen-grpc-gateway/BUILD.bazel +++ b/protoc-gen-grpc-gateway/BUILD.bazel @@ -12,8 +12,8 @@ go_library( "//internal/descriptor:go_default_library", "//protoc-gen-grpc-gateway/internal/gengateway:go_default_library", "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/protoc-gen-grpc-gateway/internal/gengateway/BUILD.bazel b/protoc-gen-grpc-gateway/internal/gengateway/BUILD.bazel index 2d407a8dc47..f19b6cd2619 100644 --- a/protoc-gen-grpc-gateway/internal/gengateway/BUILD.bazel +++ b/protoc-gen-grpc-gateway/internal/gengateway/BUILD.bazel @@ -16,8 +16,8 @@ go_library( "//internal/generator:go_default_library", "//internal/utilities:go_default_library", "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", ], ) @@ -32,7 +32,7 @@ go_test( deps = [ "//internal/descriptor:go_default_library", "//internal/httprule:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/protoc-gen-grpc-gateway/internal/gengateway/generator.go b/protoc-gen-grpc-gateway/internal/gengateway/generator.go index 633a37fbcf8..be018745fcd 100644 --- a/protoc-gen-grpc-gateway/internal/gengateway/generator.go +++ b/protoc-gen-grpc-gateway/internal/gengateway/generator.go @@ -9,10 +9,10 @@ import ( "strings" "github.com/golang/glog" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" gen "github.com/grpc-ecosystem/grpc-gateway/v2/internal/generator" + "google.golang.org/protobuf/proto" ) var ( @@ -46,7 +46,7 @@ func New(reg *descriptor.Registry, useRequestContext bool, registerFuncSuffix, p "net/http", "github.com/grpc-ecosystem/grpc-gateway/v2/runtime", "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities", - "github.com/golang/protobuf/proto", + "google.golang.org/protobuf/proto", "google.golang.org/grpc", "google.golang.org/grpc/codes", "google.golang.org/grpc/grpclog", @@ -90,8 +90,8 @@ func New(reg *descriptor.Registry, useRequestContext bool, registerFuncSuffix, p } } -func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) { - var files []*plugin.CodeGeneratorResponse_File +func (g *generator) Generate(targets []*descriptor.File) ([]*pluginpb.CodeGeneratorResponse_File, error) { + var files []*pluginpb.CodeGeneratorResponse_File for _, file := range targets { glog.V(1).Infof("Processing %s", file.GetName()) code, err := g.generate(file) @@ -114,7 +114,7 @@ func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGenerato ext := filepath.Ext(name) base := strings.TrimSuffix(name, ext) output := fmt.Sprintf("%s.pb.gw.go", base) - files = append(files, &plugin.CodeGeneratorResponse_File{ + files = append(files, &pluginpb.CodeGeneratorResponse_File{ Name: proto.String(output), Content: proto.String(string(formatted)), }) diff --git a/protoc-gen-grpc-gateway/internal/gengateway/generator_test.go b/protoc-gen-grpc-gateway/internal/gengateway/generator_test.go index 0d36ff9af19..052cd07cc8a 100644 --- a/protoc-gen-grpc-gateway/internal/gengateway/generator_test.go +++ b/protoc-gen-grpc-gateway/internal/gengateway/generator_test.go @@ -5,9 +5,9 @@ import ( "strings" "testing" - "github.com/golang/protobuf/proto" - protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" + "google.golang.org/protobuf/proto" ) func newExampleFileDescriptor() *descriptor.File { @@ -20,7 +20,7 @@ func newExampleFileDescriptor() *descriptor.File { } func newExampleFileDescriptorWithGoPkg(gp *descriptor.GoPackage) *descriptor.File { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), } msg := &descriptor.Message{ @@ -31,31 +31,31 @@ func newExampleFileDescriptorWithGoPkg(gp *descriptor.GoPackage) *descriptor.Fil File: &descriptor.File{ GoPkg: descriptor.GoPackage{ Path: "github.com/golang/protobuf/ptypes/empty", - Name: "empty", + Name: "emptypb", }, }, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } - meth1 := &protodescriptor.MethodDescriptorProto{ + meth1 := &descriptorpb.MethodDescriptorProto{ Name: proto.String("ExampleWithoutBindings"), InputType: proto.String("empty.Empty"), OutputType: proto.String("empty.Empty"), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth, meth1}, + Method: []*descriptorpb.MethodDescriptorProto{meth, meth1}, } return &descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: *gp, Messages: []*descriptor.Message{msg}, diff --git a/protoc-gen-grpc-gateway/internal/gengateway/template_test.go b/protoc-gen-grpc-gateway/internal/gengateway/template_test.go index 281fe93690b..456191597b0 100644 --- a/protoc-gen-grpc-gateway/internal/gengateway/template_test.go +++ b/protoc-gen-grpc-gateway/internal/gengateway/template_test.go @@ -4,10 +4,10 @@ import ( "strings" "testing" - "github.com/golang/protobuf/proto" - protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" + "google.golang.org/protobuf/proto" ) func crossLinkFixture(f *descriptor.File) *descriptor.File { @@ -30,28 +30,28 @@ func crossLinkFixture(f *descriptor.File) *descriptor.File { } func TestApplyTemplateHeader(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -88,44 +88,44 @@ func TestApplyTemplateHeader(t *testing.T) { } func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } - nesteddesc := &protodescriptor.DescriptorProto{ + nesteddesc := &descriptorpb.DescriptorProto{ Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(false), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool @@ -162,11 +162,11 @@ func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc, nesteddesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -252,44 +252,44 @@ func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { } func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } - nesteddesc := &protodescriptor.DescriptorProto{ + nesteddesc := &descriptorpb.DescriptorProto{ Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool @@ -326,11 +326,11 @@ func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc, nesteddesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -404,44 +404,44 @@ func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { } func TestApplyTemplateInProcess(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } - nesteddesc := &protodescriptor.DescriptorProto{ + nesteddesc := &descriptorpb.DescriptorProto{ Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } for _, spec := range []struct { clientStreaming bool @@ -501,11 +501,11 @@ func TestApplyTemplateInProcess(t *testing.T) { FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc, nesteddesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -580,25 +580,25 @@ func TestApplyTemplateInProcess(t *testing.T) { } func TestAllowPatchFeature(t *testing.T) { - updateMaskDesc := &protodescriptor.FieldDescriptorProto{ + updateMaskDesc := &descriptorpb.FieldDescriptorProto{ Name: proto.String("UpdateMask"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".google.protobuf.FieldMask"), Number: proto.Int32(1), } - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{updateMaskDesc}, + Field: []*descriptorpb.FieldDescriptorProto{updateMaskDesc}, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, @@ -609,11 +609,11 @@ func TestAllowPatchFeature(t *testing.T) { } msg.Fields = append(msg.Fields, updateMaskField) file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -662,25 +662,25 @@ func TestAllowPatchFeature(t *testing.T) { } func TestIdentifierCapitalization(t *testing.T) { - msgdesc1 := &protodescriptor.DescriptorProto{ + msgdesc1 := &descriptorpb.DescriptorProto{ Name: proto.String("Exam_pleRequest"), } - msgdesc2 := &protodescriptor.DescriptorProto{ + msgdesc2 := &descriptorpb.DescriptorProto{ Name: proto.String("example_response"), } - meth1 := &protodescriptor.MethodDescriptorProto{ + meth1 := &descriptorpb.MethodDescriptorProto{ Name: proto.String("ExampleGe2t"), InputType: proto.String("Exam_pleRequest"), OutputType: proto.String("example_response"), } - meth2 := &protodescriptor.MethodDescriptorProto{ + meth2 := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Exampl_eGet"), InputType: proto.String("Exam_pleRequest"), OutputType: proto.String("example_response"), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("Example"), - Method: []*protodescriptor.MethodDescriptorProto{meth1, meth2}, + Method: []*descriptorpb.MethodDescriptorProto{meth1, meth2}, } msg1 := &descriptor.Message{ DescriptorProto: msgdesc1, @@ -689,12 +689,12 @@ func TestIdentifierCapitalization(t *testing.T) { DescriptorProto: msgdesc2, } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc1, msgdesc2}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc1, msgdesc2}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", diff --git a/protoc-gen-grpc-gateway/main.go b/protoc-gen-grpc-gateway/main.go index 5d7a4018410..a4cfe83425e 100644 --- a/protoc-gen-grpc-gateway/main.go +++ b/protoc-gen-grpc-gateway/main.go @@ -15,11 +15,11 @@ import ( "strings" "github.com/golang/glog" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/codegenerator" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway/internal/gengateway" + "google.golang.org/protobuf/proto" ) var ( @@ -130,15 +130,15 @@ func main() { emitFiles(out) } -func emitFiles(out []*plugin.CodeGeneratorResponse_File) { - emitResp(&plugin.CodeGeneratorResponse{File: out}) +func emitFiles(out []*pluginpb.CodeGeneratorResponse_File) { + emitResp(&pluginpb.CodeGeneratorResponse{File: out}) } func emitError(err error) { - emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())}) + emitResp(&pluginpb.CodeGeneratorResponse{Error: proto.String(err.Error())}) } -func emitResp(resp *plugin.CodeGeneratorResponse) { +func emitResp(resp *pluginpb.CodeGeneratorResponse) { buf, err := proto.Marshal(resp) if err != nil { glog.Fatal(err) diff --git a/protoc-gen-swagger/BUILD.bazel b/protoc-gen-swagger/BUILD.bazel index f6f93625f2e..70429f2a89c 100644 --- a/protoc-gen-swagger/BUILD.bazel +++ b/protoc-gen-swagger/BUILD.bazel @@ -11,8 +11,8 @@ go_library( "//internal/descriptor:go_default_library", "//protoc-gen-swagger/internal/genswagger:go_default_library", "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/protoc-gen-swagger/internal/genswagger/BUILD.bazel b/protoc-gen-swagger/internal/genswagger/BUILD.bazel index a3295f7c772..f2a4c70a781 100644 --- a/protoc-gen-swagger/internal/genswagger/BUILD.bazel +++ b/protoc-gen-swagger/internal/genswagger/BUILD.bazel @@ -20,13 +20,13 @@ go_library( "//protoc-gen-swagger/options:go_default_library", "@com_github_golang_glog//:go_default_library", "@com_github_golang_protobuf//descriptor:go_default_library_gen", - "@com_github_golang_protobuf//jsonpb:go_default_library_gen", - "@com_github_golang_protobuf//proto:go_default_library", "@go_googleapis//google/rpc:status_go_proto", "@io_bazel_rules_go//proto/wkt:any_go_proto", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", "@io_bazel_rules_go//proto/wkt:struct_go_proto", + "@org_golang_google_protobuf//encoding/protojson:go_default_library", + "@org_golang_google_protobuf//proto:go_default_library", ], ) @@ -39,10 +39,12 @@ go_test( "//internal/descriptor:go_default_library", "//internal/httprule:go_default_library", "//protoc-gen-swagger/options:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", + "//runtime:go_default_library", + "@com_github_google_go_cmp//cmp:go_default_library", "@io_bazel_rules_go//proto/wkt:any_go_proto", "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", "@io_bazel_rules_go//proto/wkt:struct_go_proto", + "@org_golang_google_protobuf//proto:go_default_library", ], ) diff --git a/protoc-gen-swagger/internal/genswagger/generator.go b/protoc-gen-swagger/internal/genswagger/generator.go index b1f922de7f1..8ec0dc0a90a 100644 --- a/protoc-gen-swagger/internal/genswagger/generator.go +++ b/protoc-gen-swagger/internal/genswagger/generator.go @@ -10,15 +10,15 @@ import ( "strings" "github.com/golang/glog" - pbdescriptor "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - protocdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/golang/protobuf/ptypes/any" + legacydescriptor "github.com/golang/protobuf/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" + anypb "github.com/golang/protobuf/ptypes/any" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" gen "github.com/grpc-ecosystem/grpc-gateway/v2/internal/generator" swagger_options "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-swagger/options" - spb "google.golang.org/genproto/googleapis/rpc/status" + statuspb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/protobuf/proto" ) var ( @@ -112,7 +112,7 @@ func extensionMarshalJSON(so interface{}, extensions []extension) ([]byte, error // and thus render into what we want -- the JSON of swaggerCore with the // extensions appended. fields := []reflect.StructField{ - reflect.StructField{ // embedded + { // embedded Name: "Embedded", Type: reflect.TypeOf(so), Anonymous: true, @@ -135,8 +135,8 @@ func extensionMarshalJSON(so interface{}, extensions []extension) ([]byte, error return json.Marshal(s.Interface()) } -// encodeSwagger converts swagger file obj to plugin.CodeGeneratorResponse_File -func encodeSwagger(file *wrapper) (*plugin.CodeGeneratorResponse_File, error) { +// encodeSwagger converts swagger file obj to pluginpb.CodeGeneratorResponse_File +func encodeSwagger(file *wrapper) (*pluginpb.CodeGeneratorResponse_File, error) { var formatted bytes.Buffer enc := json.NewEncoder(&formatted) enc.SetIndent("", " ") @@ -147,14 +147,14 @@ func encodeSwagger(file *wrapper) (*plugin.CodeGeneratorResponse_File, error) { ext := filepath.Ext(name) base := strings.TrimSuffix(name, ext) output := fmt.Sprintf("%s.swagger.json", base) - return &plugin.CodeGeneratorResponse_File{ + return &pluginpb.CodeGeneratorResponse_File{ Name: proto.String(output), Content: proto.String(formatted.String()), }, nil } -func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) { - var files []*plugin.CodeGeneratorResponse_File +func (g *generator) Generate(targets []*descriptor.File) ([]*pluginpb.CodeGeneratorResponse_File, error) { + var files []*pluginpb.CodeGeneratorResponse_File if g.reg.IsAllowMerge() { var mergedTarget *descriptor.File // try to find proto leader @@ -221,18 +221,17 @@ func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGenerato // to registry (used for error-related API responses) func AddErrorDefs(reg *descriptor.Registry) error { // load internal protos - any := fileDescriptorProtoForMessage(&any.Any{}) - status := fileDescriptorProtoForMessage(&spb.Status{}) - return reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protocdescriptor.FileDescriptorProto{ + any, _ := legacydescriptor.ForMessage(&anypb.Any{}) + any.SourceCodeInfo = new(descriptorpb.SourceCodeInfo) + status, _ := legacydescriptor.ForMessage(&statuspb.Status{}) + status.SourceCodeInfo = new(descriptorpb.SourceCodeInfo) + // TODO(johanbrandhorst): Use new conversion later when possible + // any := protodesc.ToFileDescriptorProto((&anypb.Any{}).ProtoReflect().Descriptor().ParentFile()) + // status := protodesc.ToFileDescriptorProto((&statuspb.Status{}).ProtoReflect().Descriptor().ParentFile()) + return reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{ any, status, }, }) } - -func fileDescriptorProtoForMessage(msg pbdescriptor.Message) *protocdescriptor.FileDescriptorProto { - fdp, _ := pbdescriptor.ForMessage(msg) - fdp.SourceCodeInfo = &protocdescriptor.SourceCodeInfo{} - return fdp -} diff --git a/protoc-gen-swagger/internal/genswagger/template.go b/protoc-gen-swagger/internal/genswagger/template.go index 3ad93d5627e..d9ed79527be 100644 --- a/protoc-gen-swagger/internal/genswagger/template.go +++ b/protoc-gen-swagger/internal/genswagger/template.go @@ -15,72 +15,72 @@ import ( "text/template" "github.com/golang/glog" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" structpb "github.com/golang/protobuf/ptypes/struct" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/casing" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" swagger_options "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-swagger/options" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) var wktSchemas = map[string]schemaCore{ - ".google.protobuf.Timestamp": schemaCore{ + ".google.protobuf.Timestamp": { Type: "string", Format: "date-time", }, - ".google.protobuf.Duration": schemaCore{ + ".google.protobuf.Duration": { Type: "string", }, - ".google.protobuf.StringValue": schemaCore{ + ".google.protobuf.StringValue": { Type: "string", }, - ".google.protobuf.BytesValue": schemaCore{ + ".google.protobuf.BytesValue": { Type: "string", Format: "byte", }, - ".google.protobuf.Int32Value": schemaCore{ + ".google.protobuf.Int32Value": { Type: "integer", Format: "int32", }, - ".google.protobuf.UInt32Value": schemaCore{ + ".google.protobuf.UInt32Value": { Type: "integer", Format: "int64", }, - ".google.protobuf.Int64Value": schemaCore{ + ".google.protobuf.Int64Value": { Type: "string", Format: "int64", }, - ".google.protobuf.UInt64Value": schemaCore{ + ".google.protobuf.UInt64Value": { Type: "string", Format: "uint64", }, - ".google.protobuf.FloatValue": schemaCore{ + ".google.protobuf.FloatValue": { Type: "number", Format: "float", }, - ".google.protobuf.DoubleValue": schemaCore{ + ".google.protobuf.DoubleValue": { Type: "number", Format: "double", }, - ".google.protobuf.BoolValue": schemaCore{ + ".google.protobuf.BoolValue": { Type: "boolean", Format: "boolean", }, - ".google.protobuf.Empty": schemaCore{}, - ".google.protobuf.Struct": schemaCore{ + ".google.protobuf.Empty": {}, + ".google.protobuf.Struct": { Type: "object", }, - ".google.protobuf.Value": schemaCore{ + ".google.protobuf.Value": { Type: "object", }, - ".google.protobuf.ListValue": schemaCore{ + ".google.protobuf.ListValue": { Type: "array", Items: (*swaggerItemsObject)(&schemaCore{ Type: "object", }), }, - ".google.protobuf.NullValue": schemaCore{ + ".google.protobuf.NullValue": { Type: "string", }, } @@ -122,7 +122,7 @@ func messageToQueryParameters(message *descriptor.Message, reg *descriptor.Regis // queryParams converts a field to a list of swagger query parameters recursively through the use of nestedQueryParams. func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) { - return nestedQueryParams(message, field, prefix, reg, pathParams, map[string]bool{}) + return nestedQueryParams(message, field, prefix, reg, pathParams, map[string]bool{}) } // nestedQueryParams converts a field to a list of swagger query parameters recursively. @@ -147,7 +147,7 @@ func nestedQueryParams(message *descriptor.Message, field *descriptor.Field, pre } } - isEnum := field.GetType() == pbdescriptor.FieldDescriptorProto_TYPE_ENUM + isEnum := field.GetType() == descriptorpb.FieldDescriptorProto_TYPE_ENUM items := schema.Items if schema.Type != "" || isEnum { if schema.Type == "object" { @@ -226,13 +226,13 @@ func nestedQueryParams(message *descriptor.Message, field *descriptor.Field, pre if err != nil { return nil, fmt.Errorf("unknown message type %s", fieldType) } - // Check for cyclical message reference: - isCycle := touched[*msg.Name] - if isCycle { - return nil, fmt.Errorf("Recursive types are not allowed for query parameters, cycle found on %q", fieldType) - } - // Update map with the massage name so a cycle further down the recursive path can be detected. - touched[*msg.Name] = true + // Check for cyclical message reference: + isCycle := touched[*msg.Name] + if isCycle { + return nil, fmt.Errorf("Recursive types are not allowed for query parameters, cycle found on %q", fieldType) + } + // Update map with the massage name so a cycle further down the recursive path can be detected. + touched[*msg.Name] = true for _, nestedField := range msg.Fields { var fieldName string @@ -415,14 +415,14 @@ func schemaOfField(f *descriptor.Field, reg *descriptor.Registry, refs refMap) s aggregate = object } } - if fd.GetLabel() == pbdescriptor.FieldDescriptorProto_LABEL_REPEATED { + if fd.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED { aggregate = array } var props *swaggerSchemaObjectProperties switch ft := fd.GetType(); ft { - case pbdescriptor.FieldDescriptorProto_TYPE_ENUM, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE, pbdescriptor.FieldDescriptorProto_TYPE_GROUP: + case descriptorpb.FieldDescriptorProto_TYPE_ENUM, descriptorpb.FieldDescriptorProto_TYPE_MESSAGE, descriptorpb.FieldDescriptorProto_TYPE_GROUP: if wktSchema, ok := wktSchemas[fd.GetTypeName()]; ok { core = wktSchema @@ -484,46 +484,46 @@ func schemaOfField(f *descriptor.Field, reg *descriptor.Registry, refs refMap) s // primitiveSchema returns a pair of "Type" and "Format" in JSON Schema for // the given primitive field type. // The last return parameter is true iff the field type is actually primitive. -func primitiveSchema(t pbdescriptor.FieldDescriptorProto_Type) (ftype, format string, ok bool) { +func primitiveSchema(t descriptorpb.FieldDescriptorProto_Type) (ftype, format string, ok bool) { switch t { - case pbdescriptor.FieldDescriptorProto_TYPE_DOUBLE: + case descriptorpb.FieldDescriptorProto_TYPE_DOUBLE: return "number", "double", true - case pbdescriptor.FieldDescriptorProto_TYPE_FLOAT: + case descriptorpb.FieldDescriptorProto_TYPE_FLOAT: return "number", "float", true - case pbdescriptor.FieldDescriptorProto_TYPE_INT64: + case descriptorpb.FieldDescriptorProto_TYPE_INT64: return "string", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_UINT64: + case descriptorpb.FieldDescriptorProto_TYPE_UINT64: // 64bit integer types are marshaled as string in the default JSONPb marshaler. // TODO(yugui) Add an option to declare 64bit integers as int64. // // NOTE: uint64 is not a predefined format of integer type in Swagger spec. // So we cannot expect that uint64 is commonly supported by swagger processor. return "string", "uint64", true - case pbdescriptor.FieldDescriptorProto_TYPE_INT32: + case descriptorpb.FieldDescriptorProto_TYPE_INT32: return "integer", "int32", true - case pbdescriptor.FieldDescriptorProto_TYPE_FIXED64: + case descriptorpb.FieldDescriptorProto_TYPE_FIXED64: // Ditto. return "string", "uint64", true - case pbdescriptor.FieldDescriptorProto_TYPE_FIXED32: + case descriptorpb.FieldDescriptorProto_TYPE_FIXED32: // Ditto. return "integer", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_BOOL: + case descriptorpb.FieldDescriptorProto_TYPE_BOOL: return "boolean", "boolean", true - case pbdescriptor.FieldDescriptorProto_TYPE_STRING: + case descriptorpb.FieldDescriptorProto_TYPE_STRING: // NOTE: in swagger specifition, format should be empty on string type return "string", "", true - case pbdescriptor.FieldDescriptorProto_TYPE_BYTES: + case descriptorpb.FieldDescriptorProto_TYPE_BYTES: return "string", "byte", true - case pbdescriptor.FieldDescriptorProto_TYPE_UINT32: + case descriptorpb.FieldDescriptorProto_TYPE_UINT32: // Ditto. return "integer", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED32: + case descriptorpb.FieldDescriptorProto_TYPE_SFIXED32: return "integer", "int32", true - case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED64: + case descriptorpb.FieldDescriptorProto_TYPE_SFIXED64: return "string", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_SINT32: + case descriptorpb.FieldDescriptorProto_TYPE_SINT32: return "integer", "int32", true - case pbdescriptor.FieldDescriptorProto_TYPE_SINT64: + case descriptorpb.FieldDescriptorProto_TYPE_SINT64: return "string", "int64", true default: return "", "", false @@ -751,7 +751,7 @@ func renderServices(services []*descriptor.Service, paths swaggerPathsObject, re var items *swaggerItemsObject var minItems *int switch pt := parameter.Target.GetType(); pt { - case pbdescriptor.FieldDescriptorProto_TYPE_GROUP, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE: + case descriptorpb.FieldDescriptorProto_TYPE_GROUP, descriptorpb.FieldDescriptorProto_TYPE_MESSAGE: if descriptor.IsWellKnownType(parameter.Target.GetTypeName()) { if parameter.IsRepeated() { return fmt.Errorf("only primitive and enum types are allowed in repeated path parameters") @@ -764,7 +764,7 @@ func renderServices(services []*descriptor.Service, paths swaggerPathsObject, re } else { return fmt.Errorf("only primitive and well-known types are allowed in path parameters") } - case pbdescriptor.FieldDescriptorProto_TYPE_ENUM: + case descriptorpb.FieldDescriptorProto_TYPE_ENUM: enum, err := reg.LookupEnum("", parameter.Target.GetTypeName()) if err != nil { return err @@ -887,7 +887,7 @@ func renderServices(services []*descriptor.Service, paths swaggerPathsObject, re pathItemObject = swaggerPathItemObject{} } - methProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method") + methProtoPath := protoPathIndex(reflect.TypeOf((*descriptorpb.ServiceDescriptorProto)(nil)), "Method") desc := "A successful response." var responseSchema swaggerSchemaObject @@ -1162,7 +1162,7 @@ func applyTemplate(p param) (*swaggerObject, error) { renderEnumerationsAsDefinition(enums, s.Definitions, p.reg) // File itself might have some comments and metadata. - packageProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package") + packageProtoPath := protoPathIndex(reflect.TypeOf((*descriptorpb.FileDescriptorProto)(nil)), "Package") packageComments := protoComments(p.reg, p.File, nil, "Package", packageProtoPath) if err := updateSwaggerDataFromComments(p.reg, &s, p, packageComments, true); err != nil { panic(err) @@ -1395,7 +1395,7 @@ func processExtensions(inputExts map[string]*structpb.Value) ([]extension, error if !strings.HasPrefix(k, "x-") { return nil, fmt.Errorf("Extension keys need to start with \"x-\": %q", k) } - ext, err := (&jsonpb.Marshaler{Indent: " "}).MarshalToString(v) + ext, err := (&protojson.MarshalOptions{Indent: " "}).Marshal(v) if err != nil { return nil, err } @@ -1491,7 +1491,7 @@ func updateSwaggerDataFromComments(reg *descriptor.Registry, swaggerObject inter } func fieldProtoComments(reg *descriptor.Registry, msg *descriptor.Message, field *descriptor.Field) string { - protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "Field") + protoPath := protoPathIndex(reflect.TypeOf((*descriptorpb.DescriptorProto)(nil)), "Field") for i, f := range msg.Fields { if f == field { return protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index), protoPath, int32(i)) @@ -1501,7 +1501,7 @@ func fieldProtoComments(reg *descriptor.Registry, msg *descriptor.Message, field } func enumValueProtoComments(reg *descriptor.Registry, enum *descriptor.Enum) string { - protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.EnumDescriptorProto)(nil)), "Value") + protoPath := protoPathIndex(reflect.TypeOf((*descriptorpb.EnumDescriptorProto)(nil)), "Value") var comments []string for idx, value := range enum.GetValue() { name := value.GetName() @@ -1591,11 +1591,11 @@ func goTemplateComments(comment string, data interface{}, reg *descriptor.Regist return temp.String() } -var messageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "MessageType") -var nestedProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "NestedType") -var packageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package") -var serviceProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Service") -var methodProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method") +var messageProtoPath = protoPathIndex(reflect.TypeOf((*descriptorpb.FileDescriptorProto)(nil)), "MessageType") +var nestedProtoPath = protoPathIndex(reflect.TypeOf((*descriptorpb.DescriptorProto)(nil)), "NestedType") +var packageProtoPath = protoPathIndex(reflect.TypeOf((*descriptorpb.FileDescriptorProto)(nil)), "Package") +var serviceProtoPath = protoPathIndex(reflect.TypeOf((*descriptorpb.FileDescriptorProto)(nil)), "Service") +var methodProtoPath = protoPathIndex(reflect.TypeOf((*descriptorpb.ServiceDescriptorProto)(nil)), "Method") func isProtoPathMatches(paths []int32, outerPaths []int32, typeName string, typeIndex int32, fieldPaths []int32) bool { if typeName == "Package" && typeIndex == packageProtoPath { @@ -1617,7 +1617,7 @@ func isProtoPathMatches(paths []int32, outerPaths []int32, typeName string, type } paths = paths[2:] } else { - typeNameDescriptor := reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)) + typeNameDescriptor := reflect.TypeOf((*descriptorpb.FileDescriptorProto)(nil)) if len(outerPaths) > 0 { if paths[0] != messageProtoPath || paths[1] != outerPaths[0] { @@ -1636,7 +1636,7 @@ func isProtoPathMatches(paths []int32, outerPaths []int32, typeName string, type if typeName == "MessageType" { typeName = "NestedType" } - typeNameDescriptor = reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)) + typeNameDescriptor = reflect.TypeOf((*descriptorpb.DescriptorProto)(nil)) } if paths[0] != protoPathIndex(typeNameDescriptor, typeName) || paths[1] != typeIndex { @@ -1696,17 +1696,14 @@ func protoPathIndex(descriptorType reflect.Type, what string) int32 { // extractOperationOptionFromMethodDescriptor extracts the message of type // swagger_options.Operation from a given proto method's descriptor. -func extractOperationOptionFromMethodDescriptor(meth *pbdescriptor.MethodDescriptorProto) (*swagger_options.Operation, error) { +func extractOperationOptionFromMethodDescriptor(meth *descriptorpb.MethodDescriptorProto) (*swagger_options.Operation, error) { if meth.Options == nil { return nil, nil } if !proto.HasExtension(meth.Options, swagger_options.E_Openapiv2Operation) { return nil, nil } - ext, err := proto.GetExtension(meth.Options, swagger_options.E_Openapiv2Operation) - if err != nil { - return nil, err - } + ext := proto.GetExtension(meth.Options, swagger_options.E_Openapiv2Operation) opts, ok := ext.(*swagger_options.Operation) if !ok { return nil, fmt.Errorf("extension is %T; want an Operation", ext) @@ -1716,17 +1713,14 @@ func extractOperationOptionFromMethodDescriptor(meth *pbdescriptor.MethodDescrip // extractSchemaOptionFromMessageDescriptor extracts the message of type // swagger_options.Schema from a given proto message's descriptor. -func extractSchemaOptionFromMessageDescriptor(msg *pbdescriptor.DescriptorProto) (*swagger_options.Schema, error) { +func extractSchemaOptionFromMessageDescriptor(msg *descriptorpb.DescriptorProto) (*swagger_options.Schema, error) { if msg.Options == nil { return nil, nil } if !proto.HasExtension(msg.Options, swagger_options.E_Openapiv2Schema) { return nil, nil } - ext, err := proto.GetExtension(msg.Options, swagger_options.E_Openapiv2Schema) - if err != nil { - return nil, err - } + ext := proto.GetExtension(msg.Options, swagger_options.E_Openapiv2Schema) opts, ok := ext.(*swagger_options.Schema) if !ok { return nil, fmt.Errorf("extension is %T; want a Schema", ext) @@ -1736,17 +1730,14 @@ func extractSchemaOptionFromMessageDescriptor(msg *pbdescriptor.DescriptorProto) // extractSwaggerOptionFromFileDescriptor extracts the message of type // swagger_options.Swagger from a given proto method's descriptor. -func extractSwaggerOptionFromFileDescriptor(file *pbdescriptor.FileDescriptorProto) (*swagger_options.Swagger, error) { +func extractSwaggerOptionFromFileDescriptor(file *descriptorpb.FileDescriptorProto) (*swagger_options.Swagger, error) { if file.Options == nil { return nil, nil } if !proto.HasExtension(file.Options, swagger_options.E_Openapiv2Swagger) { return nil, nil } - ext, err := proto.GetExtension(file.Options, swagger_options.E_Openapiv2Swagger) - if err != nil { - return nil, err - } + ext := proto.GetExtension(file.Options, swagger_options.E_Openapiv2Swagger) opts, ok := ext.(*swagger_options.Swagger) if !ok { return nil, fmt.Errorf("extension is %T; want a Swagger object", ext) @@ -1754,17 +1745,14 @@ func extractSwaggerOptionFromFileDescriptor(file *pbdescriptor.FileDescriptorPro return opts, nil } -func extractJSONSchemaFromFieldDescriptor(fd *pbdescriptor.FieldDescriptorProto) (*swagger_options.JSONSchema, error) { +func extractJSONSchemaFromFieldDescriptor(fd *descriptorpb.FieldDescriptorProto) (*swagger_options.JSONSchema, error) { if fd.Options == nil { return nil, nil } if !proto.HasExtension(fd.Options, swagger_options.E_Openapiv2Field) { return nil, nil } - ext, err := proto.GetExtension(fd.Options, swagger_options.E_Openapiv2Field) - if err != nil { - return nil, err - } + ext := proto.GetExtension(fd.Options, swagger_options.E_Openapiv2Field) opts, ok := ext.(*swagger_options.JSONSchema) if !ok { return nil, fmt.Errorf("extension is %T; want a JSONSchema object", ext) diff --git a/protoc-gen-swagger/internal/genswagger/template_test.go b/protoc-gen-swagger/internal/genswagger/template_test.go index feeac889a1a..45aae0c0667 100644 --- a/protoc-gen-swagger/internal/genswagger/template_test.go +++ b/protoc-gen-swagger/internal/genswagger/template_test.go @@ -8,16 +8,20 @@ import ( "strings" "testing" - "github.com/golang/protobuf/proto" - protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/golang/protobuf/ptypes/any" + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" + anypb "github.com/golang/protobuf/ptypes/any" structpb "github.com/golang/protobuf/ptypes/struct" + "github.com/google/go-cmp/cmp" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" swagger_options "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-swagger/options" + "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" + "google.golang.org/protobuf/proto" ) +var marshaler = &runtime.JSONPb{} + func crossLinkFixture(f *descriptor.File) *descriptor.File { for _, m := range f.Messages { m.File = f @@ -37,9 +41,9 @@ func crossLinkFixture(f *descriptor.File) *descriptor.File { return f } -func reqFromFile(f *descriptor.File) *plugin.CodeGeneratorRequest { - return &plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{ +func reqFromFile(f *descriptor.File) *pluginpb.CodeGeneratorRequest { + return &pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{ f.FileDescriptorProto, }, FileToGenerate: []string{f.GetName()}, @@ -48,31 +52,31 @@ func reqFromFile(f *descriptor.File) *plugin.CodeGeneratorRequest { func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { type test struct { - MsgDescs []*protodescriptor.DescriptorProto + MsgDescs []*descriptorpb.DescriptorProto Message string Params []swaggerParameterObject } tests := []test{ { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("b"), - Type: protodescriptor.FieldDescriptorProto_TYPE_DOUBLE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_DOUBLE.Enum(), Number: proto.Int32(2), }, { Name: proto.String("c"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(), Number: proto.Int32(3), }, }, @@ -80,20 +84,20 @@ func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { }, Message: "ExampleMessage", Params: []swaggerParameterObject{ - swaggerParameterObject{ + { Name: "a", In: "query", Required: false, Type: "string", }, - swaggerParameterObject{ + { Name: "b", In: "query", Required: false, Type: "number", Format: "double", }, - swaggerParameterObject{ + { Name: "c", In: "query", Required: false, @@ -103,52 +107,52 @@ func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { }, }, { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("nested"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested"), Number: proto.Int32(1), }, }, }, - &protodescriptor.DescriptorProto{ + { Name: proto.String("Nested"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("deep"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested.DeepNested"), Number: proto.Int32(2), }, }, - NestedType: []*protodescriptor.DescriptorProto{{ + NestedType: []*descriptorpb.DescriptorProto{{ Name: proto.String("DeepNested"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("b"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("c"), - Type: protodescriptor.FieldDescriptorProto_TYPE_ENUM.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_ENUM.Enum(), TypeName: proto.String(".example.Nested.DeepNested.DeepEnum"), Number: proto.Int32(2), }, }, - EnumType: []*protodescriptor.EnumDescriptorProto{ + EnumType: []*descriptorpb.EnumDescriptorProto{ { Name: proto.String("DeepEnum"), - Value: []*protodescriptor.EnumValueDescriptorProto{ + Value: []*descriptorpb.EnumValueDescriptorProto{ {Name: proto.String("FALSE"), Number: proto.Int32(0)}, {Name: proto.String("TRUE"), Number: proto.Int32(1)}, }, @@ -159,19 +163,19 @@ func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { }, Message: "ExampleMessage", Params: []swaggerParameterObject{ - swaggerParameterObject{ + { Name: "nested.a", In: "query", Required: false, Type: "string", }, - swaggerParameterObject{ + { Name: "nested.deep.b", In: "query", Required: false, Type: "string", }, - swaggerParameterObject{ + { Name: "nested.deep.c", In: "query", Required: false, @@ -191,13 +195,13 @@ func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, - Service: []*protodescriptor.ServiceDescriptorProto{}, + Service: []*descriptorpb.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -205,8 +209,8 @@ func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { }, Messages: msgs, } - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, + reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) @@ -229,31 +233,31 @@ func TestMessageToQueryParametersWithEnumAsInt(t *testing.T) { func TestMessageToQueryParameters(t *testing.T) { type test struct { - MsgDescs []*protodescriptor.DescriptorProto + MsgDescs []*descriptorpb.DescriptorProto Message string Params []swaggerParameterObject } tests := []test{ { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("b"), - Type: protodescriptor.FieldDescriptorProto_TYPE_DOUBLE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_DOUBLE.Enum(), Number: proto.Int32(2), }, { Name: proto.String("c"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(), Number: proto.Int32(3), }, }, @@ -261,20 +265,20 @@ func TestMessageToQueryParameters(t *testing.T) { }, Message: "ExampleMessage", Params: []swaggerParameterObject{ - swaggerParameterObject{ + { Name: "a", In: "query", Required: false, Type: "string", }, - swaggerParameterObject{ + { Name: "b", In: "query", Required: false, Type: "number", Format: "double", }, - swaggerParameterObject{ + { Name: "c", In: "query", Required: false, @@ -284,52 +288,52 @@ func TestMessageToQueryParameters(t *testing.T) { }, }, { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("nested"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested"), Number: proto.Int32(1), }, }, }, - &protodescriptor.DescriptorProto{ + { Name: proto.String("Nested"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("deep"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.Nested.DeepNested"), Number: proto.Int32(2), }, }, - NestedType: []*protodescriptor.DescriptorProto{{ + NestedType: []*descriptorpb.DescriptorProto{{ Name: proto.String("DeepNested"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("b"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, { Name: proto.String("c"), - Type: protodescriptor.FieldDescriptorProto_TYPE_ENUM.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_ENUM.Enum(), TypeName: proto.String(".example.Nested.DeepNested.DeepEnum"), Number: proto.Int32(2), }, }, - EnumType: []*protodescriptor.EnumDescriptorProto{ + EnumType: []*descriptorpb.EnumDescriptorProto{ { Name: proto.String("DeepEnum"), - Value: []*protodescriptor.EnumValueDescriptorProto{ + Value: []*descriptorpb.EnumValueDescriptorProto{ {Name: proto.String("FALSE"), Number: proto.Int32(0)}, {Name: proto.String("TRUE"), Number: proto.Int32(1)}, }, @@ -340,19 +344,19 @@ func TestMessageToQueryParameters(t *testing.T) { }, Message: "ExampleMessage", Params: []swaggerParameterObject{ - swaggerParameterObject{ + { Name: "nested.a", In: "query", Required: false, Type: "string", }, - swaggerParameterObject{ + { Name: "nested.deep.b", In: "query", Required: false, Type: "string", }, - swaggerParameterObject{ + { Name: "nested.deep.c", In: "query", Required: false, @@ -371,13 +375,13 @@ func TestMessageToQueryParameters(t *testing.T) { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, - Service: []*protodescriptor.ServiceDescriptorProto{}, + Service: []*descriptorpb.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -385,8 +389,8 @@ func TestMessageToQueryParameters(t *testing.T) { }, Messages: msgs, } - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, + reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) @@ -412,75 +416,75 @@ func TestMessageToQueryParameters(t *testing.T) { // references to query-parameters returns an error message. func TestMessageToQueryParametersRecursive(t *testing.T) { type test struct { - MsgDescs []*protodescriptor.DescriptorProto + MsgDescs []*descriptorpb.DescriptorProto Message string } tests := []test{ - // First test: - // Here we test that a message that references it self through a field will return an error. - // Example proto: - // message DirectRecursiveMessage { - // DirectRecursiveMessage nested = 1; - // } + // First test: + // Here we test that a message that references it self through a field will return an error. + // Example proto: + // message DirectRecursiveMessage { + // DirectRecursiveMessage nested = 1; + // } { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("DirectRecursiveMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String(".example.DirectRecursiveMessage"), - Number: proto.Int32(1), + Field: []*descriptorpb.FieldDescriptorProto{ + { + Name: proto.String("nested"), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + TypeName: proto.String(".example.DirectRecursiveMessage"), + Number: proto.Int32(1), }, }, }, }, Message: "DirectRecursiveMessage", }, - // Second test: - // Here we test that a cycle through multiple messages is detected and that an error is returned. - // Sample: - // message Root { NodeMessage nested = 1; } - // message NodeMessage { CycleMessage nested = 1; } - // message CycleMessage { Root nested = 1; } + // Second test: + // Here we test that a cycle through multiple messages is detected and that an error is returned. + // Sample: + // message Root { NodeMessage nested = 1; } + // message NodeMessage { CycleMessage nested = 1; } + // message CycleMessage { Root nested = 1; } { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("RootMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String(".example.NodeMessage"), - Number: proto.Int32(1), + Field: []*descriptorpb.FieldDescriptorProto{ + { + Name: proto.String("nested"), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + TypeName: proto.String(".example.NodeMessage"), + Number: proto.Int32(1), }, }, }, - &protodescriptor.DescriptorProto{ + { Name: proto.String("NodeMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String(".example.CycleMessage"), - Number: proto.Int32(1), + Field: []*descriptorpb.FieldDescriptorProto{ + { + Name: proto.String("nested"), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + TypeName: proto.String(".example.CycleMessage"), + Number: proto.Int32(1), }, }, }, - &protodescriptor.DescriptorProto{ + { Name: proto.String("CycleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String(".example.RootMessage"), - Number: proto.Int32(1), + Field: []*descriptorpb.FieldDescriptorProto{ + { + Name: proto.String("nested"), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + TypeName: proto.String(".example.RootMessage"), + Number: proto.Int32(1), }, }, }, @@ -496,13 +500,13 @@ func TestMessageToQueryParametersRecursive(t *testing.T) { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, - Service: []*protodescriptor.ServiceDescriptorProto{}, + Service: []*descriptorpb.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -510,8 +514,8 @@ func TestMessageToQueryParametersRecursive(t *testing.T) { }, Messages: msgs, } - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, + reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) @@ -527,20 +531,20 @@ func TestMessageToQueryParametersRecursive(t *testing.T) { func TestMessageToQueryParametersWithJsonName(t *testing.T) { type test struct { - MsgDescs []*protodescriptor.DescriptorProto + MsgDescs []*descriptorpb.DescriptorProto Message string Params []swaggerParameterObject } tests := []test{ { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("test_field_a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), JsonName: proto.String("testFieldA"), }, @@ -549,7 +553,7 @@ func TestMessageToQueryParametersWithJsonName(t *testing.T) { }, Message: "ExampleMessage", Params: []swaggerParameterObject{ - swaggerParameterObject{ + { Name: "testFieldA", In: "query", Required: false, @@ -558,24 +562,24 @@ func TestMessageToQueryParametersWithJsonName(t *testing.T) { }, }, { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ + MsgDescs: []*descriptorpb.DescriptorProto{ + { Name: proto.String("SubMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("test_field_a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), JsonName: proto.String("testFieldA"), }, }, }, - &protodescriptor.DescriptorProto{ + { Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("sub_message"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String(".example.SubMessage"), Number: proto.Int32(1), JsonName: proto.String("subMessage"), @@ -585,7 +589,7 @@ func TestMessageToQueryParametersWithJsonName(t *testing.T) { }, Message: "ExampleMessage", Params: []swaggerParameterObject{ - swaggerParameterObject{ + { Name: "subMessage.testFieldA", In: "query", Required: false, @@ -603,13 +607,13 @@ func TestMessageToQueryParametersWithJsonName(t *testing.T) { msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.MsgDescs, - Service: []*protodescriptor.ServiceDescriptorProto{}, + Service: []*descriptorpb.ServiceDescriptorProto{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -617,8 +621,8 @@ func TestMessageToQueryParametersWithJsonName(t *testing.T) { }, Messages: msgs, } - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, + reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}, }) message, err := reg.LookupMsg("", ".example."+test.Message) @@ -636,29 +640,29 @@ func TestMessageToQueryParametersWithJsonName(t *testing.T) { } func TestApplyTemplateSimple(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -729,10 +733,10 @@ func TestApplyTemplateSimple(t *testing.T) { } func TestApplyTemplateMultiService(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), @@ -740,26 +744,26 @@ func TestApplyTemplateMultiService(t *testing.T) { // Create two services that have the same method name. We will test that the // operation IDs are different - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } - svc2 := &protodescriptor.ServiceDescriptorProto{ + svc2 := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("OtherService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -845,37 +849,34 @@ func TestApplyTemplateMultiService(t *testing.T) { } func TestApplyTemplateOverrideOperationID(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), - Options: &protodescriptor.MethodOptions{}, + Options: &descriptorpb.MethodOptions{}, } swaggerOperation := swagger_options.Operation{ OperationId: "MyExample", } - if err := proto.SetExtension(proto.Message(meth.Options), swagger_options.E_Openapiv2Operation, &swaggerOperation); err != nil { - t.Fatalf("proto.SetExtension(MethodDescriptorProto.Options) failed: %v", err) - } - - svc := &protodescriptor.ServiceDescriptorProto{ + proto.SetExtension(proto.Message(meth.Options), swagger_options.E_Openapiv2Operation, &swaggerOperation) + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -935,31 +936,31 @@ func TestApplyTemplateOverrideOperationID(t *testing.T) { } func TestApplyTemplateExtensions(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), - Options: &protodescriptor.MethodOptions{}, + Options: &descriptorpb.MethodOptions{}, } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - Options: &protodescriptor.FileOptions{}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, + Options: &descriptorpb.FileOptions{}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -994,44 +995,39 @@ func TestApplyTemplateExtensions(t *testing.T) { Info: &swagger_options.Info{ Title: "test", Extensions: map[string]*structpb.Value{ - "x-info-extension": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "bar"}}, + "x-info-extension": {Kind: &structpb.Value_StringValue{StringValue: "bar"}}, }, }, Extensions: map[string]*structpb.Value{ - "x-foo": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "bar"}}, - "x-bar": &structpb.Value{Kind: &structpb.Value_ListValue{ListValue: &structpb.ListValue{ + "x-foo": {Kind: &structpb.Value_StringValue{StringValue: "bar"}}, + "x-bar": {Kind: &structpb.Value_ListValue{ListValue: &structpb.ListValue{ Values: []*structpb.Value{{Kind: &structpb.Value_StringValue{StringValue: "baz"}}}, }}}, }, SecurityDefinitions: &swagger_options.SecurityDefinitions{ Security: map[string]*swagger_options.SecurityScheme{ - "somescheme": &swagger_options.SecurityScheme{ + "somescheme": { Extensions: map[string]*structpb.Value{ - "x-security-baz": &structpb.Value{Kind: &structpb.Value_BoolValue{BoolValue: true}}, + "x-security-baz": {Kind: &structpb.Value_BoolValue{BoolValue: true}}, }, }, }, }, } - if err := proto.SetExtension(proto.Message(file.FileDescriptorProto.Options), swagger_options.E_Openapiv2Swagger, &swagger); err != nil { - t.Fatalf("proto.SetExtension(FileDescriptorProto.Options) failed: %v", err) - } - + proto.SetExtension(proto.Message(file.FileDescriptorProto.Options), swagger_options.E_Openapiv2Swagger, &swagger) swaggerOperation := swagger_options.Operation{ Responses: map[string]*swagger_options.Response{ - "200": &swagger_options.Response{ + "200": { Extensions: map[string]*structpb.Value{ - "x-resp-id": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "resp1000"}}, + "x-resp-id": {Kind: &structpb.Value_StringValue{StringValue: "resp1000"}}, }, }, }, Extensions: map[string]*structpb.Value{ - "x-op-foo": &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: "baz"}}, + "x-op-foo": {Kind: &structpb.Value_StringValue{StringValue: "baz"}}, }, } - if err := proto.SetExtension(proto.Message(meth.Options), swagger_options.E_Openapiv2Operation, &swaggerOperation); err != nil { - t.Fatalf("proto.SetExtension(MethodDescriptorProto.Options) failed: %v", err) - } + proto.SetExtension(proto.Message(meth.Options), swagger_options.E_Openapiv2Operation, &swaggerOperation) reg := descriptor.NewRegistry() if err := AddErrorDefs(reg); err != nil { t.Errorf("AddErrorDefs(%#v) failed with %v; want success", reg, err) @@ -1051,11 +1047,36 @@ func TestApplyTemplateExtensions(t *testing.T) { if want, is, name := "2.0", result.Swagger, "Swagger"; !reflect.DeepEqual(is, want) { t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) } - if want, is, name := []extension{ - {key: "x-bar", value: json.RawMessage("[\n \"baz\"\n ]")}, - {key: "x-foo", value: json.RawMessage("\"bar\"")}, - }, result.extensions, "Extensions"; !reflect.DeepEqual(is, want) { - t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) + if got, want := len(result.extensions), 2; got != want { + t.Fatalf("len(applyTemplate(%#v).Extensions) = %d want to be %d", file, got, want) + } + if got, want := result.extensions[0].key, "x-bar"; got != want { + t.Errorf("applyTemplate(%#v).Extensions[0].key = %s want to be %s", file, got, want) + } + if got, want := result.extensions[1].key, "x-foo"; got != want { + t.Errorf("applyTemplate(%#v).Extensions[1].key = %s want to be %s", file, got, want) + } + { + var got []string + err = marshaler.Unmarshal(result.extensions[0].value, &got) + if err != nil { + t.Fatalf("marshaler.Unmarshal failed: %v", err) + } + want := []string{"baz"} + if diff := cmp.Diff(got, want); diff != "" { + t.Errorf(diff) + } + } + { + var got string + err = marshaler.Unmarshal(result.extensions[1].value, &got) + if err != nil { + t.Fatalf("marshaler.Unmarshal failed: %v", err) + } + want := "bar" + if diff := cmp.Diff(got, want); diff != "" { + t.Errorf(diff) + } } var scheme swaggerSecuritySchemeObject @@ -1093,44 +1114,44 @@ func TestApplyTemplateExtensions(t *testing.T) { } func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } - nesteddesc := &protodescriptor.DescriptorProto{ + nesteddesc := &descriptorpb.DescriptorProto{ Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(false), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } meth.ServerStreaming = proto.Bool(false) @@ -1155,12 +1176,12 @@ func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc, nesteddesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -1222,7 +1243,7 @@ func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { t.Errorf("AddErrorDefs(%#v) failed with %v; want success", reg, err) return } - reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) + reg.Load(&pluginpb.CodeGeneratorRequest{ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) @@ -1252,45 +1273,45 @@ func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { } func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } - nesteddesc := &protodescriptor.DescriptorProto{ + nesteddesc := &descriptorpb.DescriptorProto{ Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), ServerStreaming: proto.Bool(true), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ @@ -1313,12 +1334,12 @@ func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc, nesteddesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -1380,7 +1401,7 @@ func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { t.Errorf("AddErrorDefs(%#v) failed with %v; want success", reg, err) return } - reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) + reg.Load(&pluginpb.CodeGeneratorRequest{ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) @@ -1435,30 +1456,30 @@ func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { } func TestApplyTemplateRequestWithUnusedReferences(t *testing.T) { - reqdesc := &protodescriptor.DescriptorProto{ + reqdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("string"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), Number: proto.Int32(1), }, }, } - respdesc := &protodescriptor.DescriptorProto{ + respdesc := &descriptorpb.DescriptorProto{ Name: proto.String("EmptyMessage"), } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("EmptyMessage"), ClientStreaming: proto.Bool(false), ServerStreaming: proto.Bool(false), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } req := &descriptor.Message{ @@ -1472,12 +1493,12 @@ func TestApplyTemplateRequestWithUnusedReferences(t *testing.T) { FieldDescriptorProto: req.GetField()[0], } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{reqdesc, respdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{reqdesc, respdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -1540,7 +1561,7 @@ func TestApplyTemplateRequestWithUnusedReferences(t *testing.T) { t.Errorf("AddErrorDefs(%#v) failed with %v; want success", reg, err) return } - reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) + reg.Load(&pluginpb.CodeGeneratorRequest{ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) @@ -1563,7 +1584,7 @@ func generateFieldsForJSONReservedName() []*descriptor.Field { fields := make([]*descriptor.Field, 0) fieldName := string("json_name") fieldJSONName := string("jsonNAME") - fieldDescriptor := protodescriptor.FieldDescriptorProto{Name: &fieldName, JsonName: &fieldJSONName} + fieldDescriptor := descriptorpb.FieldDescriptorProto{Name: &fieldName, JsonName: &fieldJSONName} field := &descriptor.Field{FieldDescriptorProto: &fieldDescriptor} return append(fields, field) } @@ -1576,11 +1597,11 @@ func generateMsgsForJSONReservedName() []*descriptor.Message { fieldJSONName := "fieldAbc" messageName1 := "message1" messageType := "pkg.a.NewType" - pfd := protodescriptor.FieldDescriptorProto{Name: &fieldName, JsonName: &fieldJSONName, TypeName: &messageType} + pfd := descriptorpb.FieldDescriptorProto{Name: &fieldName, JsonName: &fieldJSONName, TypeName: &messageType} result = append(result, &descriptor.Message{ - DescriptorProto: &protodescriptor.DescriptorProto{ - Name: &messageName1, Field: []*protodescriptor.FieldDescriptorProto{&pfd}, + DescriptorProto: &descriptorpb.DescriptorProto{ + Name: &messageName1, Field: []*descriptorpb.FieldDescriptorProto{&pfd}, }, }) // The second message, its name is NewName, its type is string @@ -1590,10 +1611,10 @@ func generateMsgsForJSONReservedName() []*descriptor.Message { messageName := "NewType" field := "field_newName" fieldJSONName2 := "RESERVEDJSONNAME" - pfd2 := protodescriptor.FieldDescriptorProto{Name: &field, JsonName: &fieldJSONName2} + pfd2 := descriptorpb.FieldDescriptorProto{Name: &field, JsonName: &fieldJSONName2} result = append(result, &descriptor.Message{ - DescriptorProto: &protodescriptor.DescriptorProto{ - Name: &messageName, Field: []*protodescriptor.FieldDescriptorProto{&pfd2}, + DescriptorProto: &descriptorpb.DescriptorProto{ + Name: &messageName, Field: []*descriptorpb.FieldDescriptorProto{&pfd2}, }, }) return result @@ -1812,9 +1833,9 @@ func TestSchemaOfField(t *testing.T) { tests := []test{ { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("primitive_field"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), }, }, refs: make(refMap), @@ -1824,10 +1845,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("repeated_primitive_field"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(), }, }, refs: make(refMap), @@ -1840,10 +1861,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.StringValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1853,11 +1874,11 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("repeated_wrapped_field"), TypeName: proto.String(".google.protobuf.StringValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Label: descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(), }, }, refs: make(refMap), @@ -1870,10 +1891,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.BytesValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1884,10 +1905,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Int32Value"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1898,10 +1919,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.UInt32Value"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1912,10 +1933,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Int64Value"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1926,10 +1947,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.UInt64Value"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1940,10 +1961,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.FloatValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1954,10 +1975,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.DoubleValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1968,10 +1989,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.BoolValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1982,10 +2003,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Struct"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -1995,10 +2016,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.Value"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -2008,10 +2029,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.ListValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -2024,10 +2045,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("wrapped_field"), TypeName: proto.String(".google.protobuf.NullValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: make(refMap), @@ -2037,10 +2058,10 @@ func TestSchemaOfField(t *testing.T) { }, { field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ + FieldDescriptorProto: &descriptorpb.FieldDescriptorProto{ Name: proto.String("message_field"), TypeName: proto.String(".example.Message"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(), }, }, refs: refMap{".example.Message": struct{}{}}, @@ -2051,30 +2072,30 @@ func TestSchemaOfField(t *testing.T) { } reg := descriptor.NewRegistry() - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{ + reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{ { - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, - MessageType: []*protodescriptor.DescriptorProto{ + MessageType: []*descriptorpb.DescriptorProto{ { Name: proto.String("Message"), - Field: []*protodescriptor.FieldDescriptorProto{ + Field: []*descriptorpb.FieldDescriptorProto{ { Name: proto.String("value"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), + Type: descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(), }, }, }, }, - EnumType: []*protodescriptor.EnumDescriptorProto{ + EnumType: []*descriptorpb.EnumDescriptorProto{ { Name: proto.String("Message"), }, }, - Service: []*protodescriptor.ServiceDescriptorProto{}, + Service: []*descriptorpb.ServiceDescriptorProto{}, }, }, }) @@ -2096,35 +2117,35 @@ func TestRenderMessagesAsDefinition(t *testing.T) { tests := []struct { descr string - msgDescs []*protodescriptor.DescriptorProto + msgDescs []*descriptorpb.DescriptorProto schema map[string]swagger_options.Schema // per-message schema to add defs swaggerDefinitionsObject }{ { descr: "no swagger options", - msgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{Name: proto.String("Message")}, + msgDescs: []*descriptorpb.DescriptorProto{ + {Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{}, defs: map[string]swaggerSchemaObject{ - "Message": swaggerSchemaObject{schemaCore: schemaCore{Type: "object"}}, + "Message": {schemaCore: schemaCore{Type: "object"}}, }, }, { descr: "example option", - msgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{Name: proto.String("Message")}, + msgDescs: []*descriptorpb.DescriptorProto{ + {Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ - "Message": swagger_options.Schema{ - Example: &any.Any{ + "Message": { + Example: &anypb.Any{ TypeUrl: "this_isnt_used", Value: []byte(`{"foo":"bar"}`), }, }, }, defs: map[string]swaggerSchemaObject{ - "Message": swaggerSchemaObject{schemaCore: schemaCore{ + "Message": {schemaCore: schemaCore{ Type: "object", Example: json.RawMessage(`{"foo":"bar"}`), }}, @@ -2132,18 +2153,18 @@ func TestRenderMessagesAsDefinition(t *testing.T) { }, { descr: "example option with something non-json", - msgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{Name: proto.String("Message")}, + msgDescs: []*descriptorpb.DescriptorProto{ + {Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ - "Message": swagger_options.Schema{ - Example: &any.Any{ + "Message": { + Example: &anypb.Any{ Value: []byte(`XXXX anything goes XXXX`), }, }, }, defs: map[string]swaggerSchemaObject{ - "Message": swaggerSchemaObject{schemaCore: schemaCore{ + "Message": {schemaCore: schemaCore{ Type: "object", Example: json.RawMessage(`XXXX anything goes XXXX`), }}, @@ -2151,11 +2172,11 @@ func TestRenderMessagesAsDefinition(t *testing.T) { }, { descr: "external docs option", - msgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{Name: proto.String("Message")}, + msgDescs: []*descriptorpb.DescriptorProto{ + {Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ - "Message": swagger_options.Schema{ + "Message": { ExternalDocs: &swagger_options.ExternalDocumentation{ Description: "glorious docs", Url: "https://nada", @@ -2163,7 +2184,7 @@ func TestRenderMessagesAsDefinition(t *testing.T) { }, }, defs: map[string]swaggerSchemaObject{ - "Message": swaggerSchemaObject{ + "Message": { schemaCore: schemaCore{ Type: "object", }, @@ -2176,11 +2197,11 @@ func TestRenderMessagesAsDefinition(t *testing.T) { }, { descr: "JSONSchema options", - msgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{Name: proto.String("Message")}, + msgDescs: []*descriptorpb.DescriptorProto{ + {Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ - "Message": swagger_options.Schema{ + "Message": { JsonSchema: &swagger_options.JSONSchema{ Title: "title", Description: "desc", @@ -2203,7 +2224,7 @@ func TestRenderMessagesAsDefinition(t *testing.T) { }, }, defs: map[string]swaggerSchemaObject{ - "Message": swaggerSchemaObject{ + "Message": { schemaCore: schemaCore{ Type: "object", }, @@ -2234,25 +2255,25 @@ func TestRenderMessagesAsDefinition(t *testing.T) { msgs := []*descriptor.Message{} for _, msgdesc := range test.msgDescs { - msgdesc.Options = &protodescriptor.MessageOptions{} + msgdesc.Options = &descriptorpb.MessageOptions{} msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } reg := descriptor.NewRegistry() file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.msgDescs, - EnumType: []*protodescriptor.EnumDescriptorProto{}, - Service: []*protodescriptor.ServiceDescriptorProto{}, + EnumType: []*descriptorpb.EnumDescriptorProto{}, + Service: []*descriptorpb.ServiceDescriptorProto{}, }, Messages: msgs, } - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, + reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}, }) msgMap := map[string]*descriptor.Message{} @@ -2265,10 +2286,7 @@ func TestRenderMessagesAsDefinition(t *testing.T) { msgMap[msg.FQMN()] = msg if schema, ok := test.schema[name]; ok { - err := proto.SetExtension(d.Options, swagger_options.E_Openapiv2Schema, &schema) - if err != nil { - t.Fatalf("SetExtension(%s, ...) returned error: %v", msg, err) - } + proto.SetExtension(d.Options, swagger_options.E_Openapiv2Schema, &schema) } } @@ -2453,18 +2471,18 @@ func TestUpdateSwaggerDataFromComments(t *testing.T) { func TestMessageOptionsWithGoTemplate(t *testing.T) { tests := []struct { descr string - msgDescs []*protodescriptor.DescriptorProto + msgDescs []*descriptorpb.DescriptorProto schema map[string]swagger_options.Schema // per-message schema to add defs swaggerDefinitionsObject useGoTemplate bool }{ { descr: "external docs option", - msgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{Name: proto.String("Message")}, + msgDescs: []*descriptorpb.DescriptorProto{ + {Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ - "Message": swagger_options.Schema{ + "Message": { JsonSchema: &swagger_options.JSONSchema{ Title: "{{.Name}}", Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", @@ -2475,7 +2493,7 @@ func TestMessageOptionsWithGoTemplate(t *testing.T) { }, }, defs: map[string]swaggerSchemaObject{ - "Message": swaggerSchemaObject{ + "Message": { schemaCore: schemaCore{ Type: "object", }, @@ -2490,11 +2508,11 @@ func TestMessageOptionsWithGoTemplate(t *testing.T) { }, { descr: "external docs option", - msgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{Name: proto.String("Message")}, + msgDescs: []*descriptorpb.DescriptorProto{ + {Name: proto.String("Message")}, }, schema: map[string]swagger_options.Schema{ - "Message": swagger_options.Schema{ + "Message": { JsonSchema: &swagger_options.JSONSchema{ Title: "{{.Name}}", Description: "Description {{with \"which means nothing\"}}{{printf \"%q\" .}}{{end}}", @@ -2505,7 +2523,7 @@ func TestMessageOptionsWithGoTemplate(t *testing.T) { }, }, defs: map[string]swaggerSchemaObject{ - "Message": swaggerSchemaObject{ + "Message": { schemaCore: schemaCore{ Type: "object", }, @@ -2525,26 +2543,26 @@ func TestMessageOptionsWithGoTemplate(t *testing.T) { msgs := []*descriptor.Message{} for _, msgdesc := range test.msgDescs { - msgdesc.Options = &protodescriptor.MessageOptions{} + msgdesc.Options = &descriptorpb.MessageOptions{} msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) } reg := descriptor.NewRegistry() reg.SetUseGoTemplate(test.useGoTemplate) file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{}, MessageType: test.msgDescs, - EnumType: []*protodescriptor.EnumDescriptorProto{}, - Service: []*protodescriptor.ServiceDescriptorProto{}, + EnumType: []*descriptorpb.EnumDescriptorProto{}, + Service: []*descriptorpb.ServiceDescriptorProto{}, }, Messages: msgs, } - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, + reg.Load(&pluginpb.CodeGeneratorRequest{ + ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}, }) msgMap := map[string]*descriptor.Message{} @@ -2557,10 +2575,7 @@ func TestMessageOptionsWithGoTemplate(t *testing.T) { msgMap[msg.FQMN()] = msg if schema, ok := test.schema[name]; ok { - err := proto.SetExtension(d.Options, swagger_options.E_Openapiv2Schema, &schema) - if err != nil { - t.Fatalf("SetExtension(%s, ...) returned error: %v", msg, err) - } + proto.SetExtension(d.Options, swagger_options.E_Openapiv2Schema, &schema) } } @@ -2576,18 +2591,18 @@ func TestMessageOptionsWithGoTemplate(t *testing.T) { } func TestTemplateWithoutErrorDefinition(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ + msgdesc := &descriptorpb.DescriptorProto{ Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{}, + Field: []*descriptorpb.FieldDescriptorProto{}, } - meth := &protodescriptor.MethodDescriptorProto{ + meth := &descriptorpb.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } - svc := &protodescriptor.ServiceDescriptorProto{ + svc := &descriptorpb.ServiceDescriptorProto{ Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, + Method: []*descriptorpb.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ @@ -2595,12 +2610,12 @@ func TestTemplateWithoutErrorDefinition(t *testing.T) { } file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, + FileDescriptorProto: &descriptorpb.FileDescriptorProto{ + SourceCodeInfo: &descriptorpb.SourceCodeInfo{}, Name: proto.String("example.proto"), Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, + MessageType: []*descriptorpb.DescriptorProto{msgdesc, msgdesc}, + Service: []*descriptorpb.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", @@ -2634,7 +2649,7 @@ func TestTemplateWithoutErrorDefinition(t *testing.T) { }, } reg := descriptor.NewRegistry() - reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) + reg.Load(&pluginpb.CodeGeneratorRequest{ProtoFile: []*descriptorpb.FileDescriptorProto{file.FileDescriptorProto}}) result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) diff --git a/protoc-gen-swagger/main.go b/protoc-gen-swagger/main.go index d44999a9ee0..017510fae9b 100644 --- a/protoc-gen-swagger/main.go +++ b/protoc-gen-swagger/main.go @@ -7,11 +7,11 @@ import ( "strings" "github.com/golang/glog" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" + pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/codegenerator" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor" "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-swagger/internal/genswagger" + "google.golang.org/protobuf/proto" ) var ( @@ -131,15 +131,15 @@ func main() { emitFiles(out) } -func emitFiles(out []*plugin.CodeGeneratorResponse_File) { - emitResp(&plugin.CodeGeneratorResponse{File: out}) +func emitFiles(out []*pluginpb.CodeGeneratorResponse_File) { + emitResp(&pluginpb.CodeGeneratorResponse{File: out}) } func emitError(err error) { - emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())}) + emitResp(&pluginpb.CodeGeneratorResponse{Error: proto.String(err.Error())}) } -func emitResp(resp *plugin.CodeGeneratorResponse) { +func emitResp(resp *pluginpb.CodeGeneratorResponse) { buf, err := proto.Marshal(resp) if err != nil { glog.Fatal(err) diff --git a/runtime/BUILD.bazel b/runtime/BUILD.bazel index 236a8b349fe..2d971edd2f3 100644 --- a/runtime/BUILD.bazel +++ b/runtime/BUILD.bazel @@ -25,8 +25,6 @@ go_library( importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/runtime", deps = [ "//internal/utilities:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library_gen", - "@com_github_golang_protobuf//proto:go_default_library", "@com_github_golang_protobuf//ptypes:go_default_library_gen", "@go_googleapis//google/api:httpbody_go_proto", "@io_bazel_rules_go//proto/wkt:duration_go_proto", @@ -37,6 +35,7 @@ go_library( "@org_golang_google_grpc//grpclog:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_golang_google_protobuf//encoding/protojson:go_default_library", "@org_golang_google_protobuf//proto:go_default_library", "@org_golang_google_protobuf//reflect/protoreflect:go_default_library", "@org_golang_google_protobuf//reflect/protoregistry:go_default_library", @@ -65,13 +64,12 @@ go_test( deps = [ "//internal/utilities:go_default_library", "//runtime/internal/examplepb:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library_gen", - "@com_github_golang_protobuf//proto:go_default_library", "@com_github_golang_protobuf//ptypes:go_default_library_gen", "@com_github_google_go_cmp//cmp:go_default_library", "@com_github_google_go_cmp//cmp/cmpopts:go_default_library", "@go_googleapis//google/api:httpbody_go_proto", "@go_googleapis//google/rpc:errdetails_go_proto", + "@go_googleapis//google/rpc:status_go_proto", "@io_bazel_rules_go//proto/wkt:duration_go_proto", "@io_bazel_rules_go//proto/wkt:empty_go_proto", "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", @@ -82,6 +80,7 @@ go_test( "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_golang_google_protobuf//encoding/protojson:go_default_library", "@org_golang_google_protobuf//proto:go_default_library", "@org_golang_google_protobuf//testing/protocmp:go_default_library", ], diff --git a/runtime/convert.go b/runtime/convert.go index 2c279344dc4..e122dd33949 100644 --- a/runtime/convert.go +++ b/runtime/convert.go @@ -6,10 +6,10 @@ import ( "strconv" "strings" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" + durationpb "github.com/golang/protobuf/ptypes/duration" + timestamppb "github.com/golang/protobuf/ptypes/timestamp" + wrapperspb "github.com/golang/protobuf/ptypes/wrappers" + "google.golang.org/protobuf/encoding/protojson" ) // String just returns the given string. @@ -205,9 +205,10 @@ func BytesSlice(val, sep string) ([][]byte, error) { } // Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp. -func Timestamp(val string) (*timestamp.Timestamp, error) { - var r timestamp.Timestamp - err := jsonpb.UnmarshalString(val, &r) +func Timestamp(val string) (*timestamppb.Timestamp, error) { + var r timestamppb.Timestamp + unmarshaler := &protojson.UnmarshalOptions{} + err := unmarshaler.Unmarshal([]byte(val), &r) if err != nil { return nil, err } @@ -215,9 +216,10 @@ func Timestamp(val string) (*timestamp.Timestamp, error) { } // Duration converts the given string into a timestamp.Duration. -func Duration(val string) (*duration.Duration, error) { - var r duration.Duration - err := jsonpb.UnmarshalString(val, &r) +func Duration(val string) (*durationpb.Duration, error) { + var r durationpb.Duration + unmarshaler := &protojson.UnmarshalOptions{} + err := unmarshaler.Unmarshal([]byte(val), &r) if err != nil { return nil, err } @@ -265,54 +267,54 @@ func EnumSlice(val, sep string, enumValMap map[string]int32) ([]int32, error) { */ // StringValue well-known type support as wrapper around string type -func StringValue(val string) (*wrappers.StringValue, error) { - return &wrappers.StringValue{Value: val}, nil +func StringValue(val string) (*wrapperspb.StringValue, error) { + return &wrapperspb.StringValue{Value: val}, nil } // FloatValue well-known type support as wrapper around float32 type -func FloatValue(val string) (*wrappers.FloatValue, error) { +func FloatValue(val string) (*wrapperspb.FloatValue, error) { parsedVal, err := Float32(val) - return &wrappers.FloatValue{Value: parsedVal}, err + return &wrapperspb.FloatValue{Value: parsedVal}, err } // DoubleValue well-known type support as wrapper around float64 type -func DoubleValue(val string) (*wrappers.DoubleValue, error) { +func DoubleValue(val string) (*wrapperspb.DoubleValue, error) { parsedVal, err := Float64(val) - return &wrappers.DoubleValue{Value: parsedVal}, err + return &wrapperspb.DoubleValue{Value: parsedVal}, err } // BoolValue well-known type support as wrapper around bool type -func BoolValue(val string) (*wrappers.BoolValue, error) { +func BoolValue(val string) (*wrapperspb.BoolValue, error) { parsedVal, err := Bool(val) - return &wrappers.BoolValue{Value: parsedVal}, err + return &wrapperspb.BoolValue{Value: parsedVal}, err } // Int32Value well-known type support as wrapper around int32 type -func Int32Value(val string) (*wrappers.Int32Value, error) { +func Int32Value(val string) (*wrapperspb.Int32Value, error) { parsedVal, err := Int32(val) - return &wrappers.Int32Value{Value: parsedVal}, err + return &wrapperspb.Int32Value{Value: parsedVal}, err } // UInt32Value well-known type support as wrapper around uint32 type -func UInt32Value(val string) (*wrappers.UInt32Value, error) { +func UInt32Value(val string) (*wrapperspb.UInt32Value, error) { parsedVal, err := Uint32(val) - return &wrappers.UInt32Value{Value: parsedVal}, err + return &wrapperspb.UInt32Value{Value: parsedVal}, err } // Int64Value well-known type support as wrapper around int64 type -func Int64Value(val string) (*wrappers.Int64Value, error) { +func Int64Value(val string) (*wrapperspb.Int64Value, error) { parsedVal, err := Int64(val) - return &wrappers.Int64Value{Value: parsedVal}, err + return &wrapperspb.Int64Value{Value: parsedVal}, err } // UInt64Value well-known type support as wrapper around uint64 type -func UInt64Value(val string) (*wrappers.UInt64Value, error) { +func UInt64Value(val string) (*wrapperspb.UInt64Value, error) { parsedVal, err := Uint64(val) - return &wrappers.UInt64Value{Value: parsedVal}, err + return &wrapperspb.UInt64Value{Value: parsedVal}, err } // BytesValue well-known type support as wrapper around bytes[] type -func BytesValue(val string) (*wrappers.BytesValue, error) { +func BytesValue(val string) (*wrapperspb.BytesValue, error) { parsedVal, err := Bytes(val) - return &wrappers.BytesValue{Value: parsedVal}, err + return &wrapperspb.BytesValue{Value: parsedVal}, err } diff --git a/runtime/convert_test.go b/runtime/convert_test.go index 4e61f0553ba..a4148c7aedc 100644 --- a/runtime/convert_test.go +++ b/runtime/convert_test.go @@ -1,71 +1,59 @@ package runtime_test import ( - "encoding/json" - "fmt" - "reflect" "testing" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/timestamp" + durationpb "github.com/golang/protobuf/ptypes/duration" + timestamppb "github.com/golang/protobuf/ptypes/timestamp" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" + "google.golang.org/protobuf/proto" ) func TestConvertTimestamp(t *testing.T) { specs := []struct { name string input string - output *timestamp.Timestamp - wanterr error + output *timestamppb.Timestamp + wanterr bool }{ { name: "a valid RFC3339 timestamp", input: `"2016-05-10T10:19:13.123Z"`, - output: ×tamp.Timestamp{ + output: ×tamppb.Timestamp{ Seconds: 1462875553, Nanos: 123000000, }, - wanterr: nil, + wanterr: false, }, { name: "invalid timestamp", input: `"05-10-2016T10:19:13.123Z"`, output: nil, - wanterr: fmt.Errorf(`bad Timestamp: parsing time "05-10-2016T10:19:13.123Z" as "2006-01-02T15:04:05.999999999Z07:00": cannot parse "0-2016T10:19:13.123Z" as "2006"`), + wanterr: true, }, { - name: "JSON number", - input: "123", - output: nil, - wanterr: &json.UnmarshalTypeError{ - Value: "number", - Type: reflect.TypeOf("123"), - Offset: 3, - }, + name: "JSON number", + input: "123", + output: nil, + wanterr: true, }, { - name: "JSON bool", - input: "true", - output: nil, - wanterr: &json.UnmarshalTypeError{ - Value: "bool", - Type: reflect.TypeOf("123"), - Offset: 4, - }, + name: "JSON bool", + input: "true", + output: nil, + wanterr: true, }, } for _, spec := range specs { t.Run(spec.name, func(t *testing.T) { ts, err := runtime.Timestamp(spec.input) - if spec.wanterr != nil { - if !reflect.DeepEqual(err, spec.wanterr) { - t.Errorf("got unexpected error\n%#v\nexpected\n%#v", err, spec.wanterr) - } - return - } - if !proto.Equal(ts, spec.output) { + switch { + case err != nil && !spec.wanterr: + t.Errorf("got unexpected error\n%#v", err) + case err == nil && spec.wanterr: + t.Errorf("did not error when expecte") + case !proto.Equal(ts, spec.output): t.Errorf( "when testing %s; got\n%#v\nexpected\n%#v", spec.name, @@ -81,56 +69,47 @@ func TestConvertDuration(t *testing.T) { specs := []struct { name string input string - output *duration.Duration - wanterr error + output *durationpb.Duration + wanterr bool }{ { name: "a valid duration", input: `"123.456s"`, - output: &duration.Duration{ + output: &durationpb.Duration{ Seconds: 123, Nanos: 456000000, }, - wanterr: nil, + wanterr: false, }, { name: "invalid duration", input: `"123years"`, output: nil, - wanterr: fmt.Errorf(`bad Duration: time: unknown unit years in duration 123years`), + wanterr: true, }, { - name: "JSON number", - input: "123", - output: nil, - wanterr: &json.UnmarshalTypeError{ - Value: "number", - Type: reflect.TypeOf("123"), - Offset: 3, - }, + name: "JSON number", + input: "123", + output: nil, + wanterr: true, }, { - name: "JSON bool", - input: "true", - output: nil, - wanterr: &json.UnmarshalTypeError{ - Value: "bool", - Type: reflect.TypeOf("123"), - Offset: 4, - }, + name: "JSON bool", + input: "true", + output: nil, + wanterr: true, }, } for _, spec := range specs { t.Run(spec.name, func(t *testing.T) { ts, err := runtime.Duration(spec.input) - if spec.wanterr != nil { - if !reflect.DeepEqual(err, spec.wanterr) { - t.Errorf("got unexpected error\n%#v\nexpected\n%#v", err, spec.wanterr) - } - return - } - if !proto.Equal(ts, spec.output) { + switch { + case err != nil && !spec.wanterr: + t.Errorf("got unexpected error\n%#v", err) + case err == nil && spec.wanterr: + t.Errorf("did not error when expecte") + case !proto.Equal(ts, spec.output): t.Errorf( "when testing %s; got\n%#v\nexpected\n%#v", spec.name, diff --git a/runtime/errors_test.go b/runtime/errors_test.go index 5ba54eb97db..02463ee8483 100644 --- a/runtime/errors_test.go +++ b/runtime/errors_test.go @@ -2,15 +2,16 @@ package runtime_test import ( "context" - "encoding/json" "fmt" "net/http" "net/http/httptest" + "strconv" "strings" "testing" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/genproto/googleapis/rpc/errdetails" + statuspb "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -22,7 +23,7 @@ func TestDefaultHTTPError(t *testing.T) { &errdetails.PreconditionFailure{}, ) - for _, spec := range []struct { + for i, spec := range []struct { err error status int msg string @@ -60,41 +61,39 @@ func TestDefaultHTTPError(t *testing.T) { msg: "example error", }, } { - w := httptest.NewRecorder() - req, _ := http.NewRequest("", "", nil) // Pass in an empty request to match the signature - mux := runtime.NewServeMux() - runtime.HTTPError(ctx, mux, &runtime.JSONPb{}, w, req, spec.err) + t.Run(strconv.Itoa(i), func(t *testing.T) { + w := httptest.NewRecorder() + req, _ := http.NewRequest("", "", nil) // Pass in an empty request to match the signature + mux := runtime.NewServeMux() + marshaler := &runtime.JSONPb{} + runtime.HTTPError(ctx, mux, marshaler, w, req, spec.err) - if got, want := w.Header().Get("Content-Type"), "application/json"; got != want { - t.Errorf(`w.Header().Get("Content-Type") = %q; want %q; on spec.err=%v`, got, want, spec.err) - } - if got, want := w.Code, spec.status; got != want { - t.Errorf("w.Code = %d; want %d", got, want) - } - - body := make(map[string]interface{}) - if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { - t.Errorf("json.Unmarshal(%q, &body) failed with %v; want success", w.Body.Bytes(), err) - continue - } - - if got, want := body["message"].(string), spec.msg; !strings.Contains(got, want) { - t.Errorf(`body["message"] = %q; want %q; on spec.err=%v`, got, want, spec.err) - } + if got, want := w.Header().Get("Content-Type"), "application/json"; got != want { + t.Errorf(`w.Header().Get("Content-Type") = %q; want %q; on spec.err=%v`, got, want, spec.err) + } + if got, want := w.Code, spec.status; got != want { + t.Errorf("w.Code = %d; want %d", got, want) + } - if spec.details != "" { - details, ok := body["details"].([]interface{}) - if !ok { - t.Errorf(`body["details"] = %T; want %T`, body["details"], []interface{}{}) - continue + var st statuspb.Status + if err := marshaler.Unmarshal(w.Body.Bytes(), &st); err != nil { + t.Errorf("marshaler.Unmarshal(%q, &body) failed with %v; want success", w.Body.Bytes(), err) + return } - if len(details) != 1 { - t.Errorf(`len(body["details"]) = %v; want 1`, len(details)) - continue + + if got, want := st.Message, spec.msg; !strings.Contains(got, want) { + t.Errorf(`st.Message = %q; want %q; on spec.err=%v`, got, want, spec.err) } - if details[0].(map[string]interface{})["@type"] != spec.details { - t.Errorf(`details.@type = %s; want %s`, details[0].(map[string]interface{})["@type"], spec.details) + + if spec.details != "" { + if len(st.Details) != 1 { + t.Errorf(`len(st.Details) = %v; want 1`, len(st.Details)) + return + } + if st.Details[0].TypeUrl != spec.details { + t.Errorf(`details.type_url = %s; want %s`, st.Details[0].TypeUrl, spec.details) + } } - } + }) } } diff --git a/runtime/handler.go b/runtime/handler.go index 4cbf8f46259..9c445e83890 100644 --- a/runtime/handler.go +++ b/runtime/handler.go @@ -7,11 +7,11 @@ import ( "net/http" "net/textproto" - "github.com/golang/protobuf/proto" "google.golang.org/genproto/googleapis/api/httpbody" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // ForwardResponseStream forwards the stream from gRPC server to REST client. @@ -61,22 +61,20 @@ func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshal } var buf []byte + httpBody, isHTTPBody := resp.(*httpbody.HttpBody) switch { case resp == nil: buf, err = marshaler.Marshal(errorChunk(status.New(codes.Internal, "empty response"))) + case isHTTPBody: + buf = httpBody.GetData() + w.Header().Set("Content-Type", httpBody.GetContentType()) default: - if httpBody, ok := resp.(*httpbody.HttpBody); ok { - buf = httpBody.GetData() - w.Header().Set("Content-Type", httpBody.GetContentType()) - } else { - result := map[string]interface{}{"result": resp} - if rb, ok := resp.(responseBody); ok { - result["result"] = rb.XXX_ResponseBody() - } - - buf, err = marshaler.Marshal(result) + result := map[string]interface{}{"result": resp} + if rb, ok := resp.(responseBody); ok { + result["result"] = rb.XXX_ResponseBody() } + buf, err = marshaler.Marshal(result) } if err != nil { diff --git a/runtime/handler_test.go b/runtime/handler_test.go index 270cfab9cc9..3a7aec6c8f2 100644 --- a/runtime/handler_test.go +++ b/runtime/handler_test.go @@ -8,12 +8,12 @@ import ( "net/http/httptest" "testing" - "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" pb "github.com/grpc-ecosystem/grpc-gateway/v2/runtime/internal/examplepb" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) type fakeReponseBodyWrapper struct { diff --git a/runtime/marshal_httpbodyproto.go b/runtime/marshal_httpbodyproto.go index f55285b5d6c..1f13f4d5f67 100644 --- a/runtime/marshal_httpbodyproto.go +++ b/runtime/marshal_httpbodyproto.go @@ -4,10 +4,10 @@ import ( "google.golang.org/genproto/googleapis/api/httpbody" ) -// SetHTTPBodyMarshaler overwrite the default marshaler with the HTTPBodyMarshaler +// SetHTTPBodyMarshaler overwrites the default marshaler with the HTTPBodyMarshaler func SetHTTPBodyMarshaler(serveMux *ServeMux) { serveMux.marshalers.mimeMap[MIMEWildcard] = &HTTPBodyMarshaler{ - Marshaler: &JSONPb{OrigName: true}, + Marshaler: defaultMarshaler, } } diff --git a/runtime/marshal_httpbodyproto_test.go b/runtime/marshal_httpbodyproto_test.go index 331fd28d3d7..4782d085415 100644 --- a/runtime/marshal_httpbodyproto_test.go +++ b/runtime/marshal_httpbodyproto_test.go @@ -6,12 +6,15 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/genproto/googleapis/api/httpbody" + "google.golang.org/protobuf/encoding/protojson" ) func TestHTTPBodyContentType(t *testing.T) { m := runtime.HTTPBodyMarshaler{ &runtime.JSONPb{ - OrigName: true, + MarshalOptions: protojson.MarshalOptions{ + UseProtoNames: true, + }, }, } expected := "CustomContentType" @@ -31,7 +34,9 @@ func TestHTTPBodyContentType(t *testing.T) { func TestHTTPBodyMarshal(t *testing.T) { m := runtime.HTTPBodyMarshaler{ &runtime.JSONPb{ - OrigName: true, + MarshalOptions: protojson.MarshalOptions{ + UseProtoNames: true, + }, }, } expected := []byte("Some test") diff --git a/runtime/marshal_json_test.go b/runtime/marshal_json_test.go index 1339f928155..67a0370a2b8 100644 --- a/runtime/marshal_json_test.go +++ b/runtime/marshal_json_test.go @@ -7,13 +7,13 @@ import ( "strings" "testing" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" + emptypb "github.com/golang/protobuf/ptypes/empty" structpb "github.com/golang/protobuf/ptypes/struct" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" + timestamppb "github.com/golang/protobuf/ptypes/timestamp" + wrapperspb "github.com/golang/protobuf/ptypes/wrappers" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime/internal/examplepb" + "google.golang.org/protobuf/proto" ) func TestJSONBuiltinMarshal(t *testing.T) { @@ -210,7 +210,7 @@ var ( {data: true, json: "true"}, {data: proto.Bool(true), json: "true"}, {data: (*string)(nil), json: "null"}, - {data: new(empty.Empty), json: "{}"}, + {data: new(emptypb.Empty), json: "{}"}, {data: examplepb.NumericEnum_ONE, json: "1"}, {data: nil, json: "null"}, {data: (*string)(nil), json: "null"}, @@ -238,14 +238,14 @@ var ( json: `"abc"`, }, { - data: ×tamp.Timestamp{ + data: ×tamppb.Timestamp{ Seconds: 1462875553, Nanos: 123000000, }, json: `"2016-05-10T10:19:13.123Z"`, }, { - data: &wrappers.Int32Value{Value: 123}, + data: &wrapperspb.Int32Value{Value: 123}, json: "123", }, { diff --git a/runtime/marshal_jsonpb.go b/runtime/marshal_jsonpb.go index c2fb9dd9d47..c5f06120c74 100644 --- a/runtime/marshal_jsonpb.go +++ b/runtime/marshal_jsonpb.go @@ -7,17 +7,20 @@ import ( "io" "reflect" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) // JSONPb is a Marshaler which marshals/unmarshals into/from JSON -// with the "github.com/golang/protobuf/jsonpb". -// It supports fully functionality of protobuf unlike JSONBuiltin. +// with the "google.golang.org/protobuf/encoding/protojson" marshaler. +// It supports the full functionality of protobuf unlike JSONBuiltin. // // The NewDecoder method returns a DecoderWrapper, so the underlying // *json.Decoder methods can be used. -type JSONPb jsonpb.Marshaler +type JSONPb struct { + protojson.MarshalOptions + protojson.UnmarshalOptions +} // ContentType always returns "application/json". func (*JSONPb) ContentType() string { @@ -47,7 +50,13 @@ func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error { _, err = w.Write(buf) return err } - return (*jsonpb.Marshaler)(j).Marshal(w, p) + b, err := j.MarshalOptions.Marshal(p) + if err != nil { + return err + } + + _, err = w.Write(b) + return err } var ( @@ -74,7 +83,7 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { if rv.Kind() == reflect.Slice { if rv.IsNil() { - if j.EmitDefaults { + if j.EmitUnpopulated { return []byte("[]"), nil } return []byte("null"), nil @@ -93,7 +102,7 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { return nil, err } } - if err = (*jsonpb.Marshaler)(j).Marshal(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { + if err = j.marshalTo(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { return nil, err } } @@ -120,7 +129,7 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { } return json.Marshal(m) } - if enum, ok := rv.Interface().(protoEnum); ok && !j.EnumsAsInts { + if enum, ok := rv.Interface().(protoEnum); ok && !j.UseEnumNumbers { return json.Marshal(enum.String()) } return json.Marshal(rv.Interface()) @@ -172,8 +181,18 @@ func decodeJSONPb(d *json.Decoder, v interface{}) error { if !ok { return decodeNonProtoField(d, v) } - unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields} - return unmarshaler.UnmarshalNext(d, p) + + // Decode into bytes for marshalling + var b json.RawMessage + err := d.Decode(&b) + if err != nil { + return err + } + + unmarshaler := &protojson.UnmarshalOptions{ + DiscardUnknown: allowUnknownFields, + } + return unmarshaler.Unmarshal([]byte(b), p) } func decodeNonProtoField(d *json.Decoder, v interface{}) error { @@ -186,8 +205,17 @@ func decodeNonProtoField(d *json.Decoder, v interface{}) error { rv.Set(reflect.New(rv.Type().Elem())) } if rv.Type().ConvertibleTo(typeProtoMessage) { - unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields} - return unmarshaler.UnmarshalNext(d, rv.Interface().(proto.Message)) + // Decode into bytes for marshalling + var b json.RawMessage + err := d.Decode(&b) + if err != nil { + return err + } + + unmarshaler := &protojson.UnmarshalOptions{ + DiscardUnknown: allowUnknownFields, + } + return unmarshaler.Unmarshal([]byte(b), rv.Interface().(proto.Message)) } rv = rv.Elem() } @@ -218,6 +246,23 @@ func decodeNonProtoField(d *json.Decoder, v interface{}) error { } return nil } + if rv.Kind() == reflect.Slice { + var sl []json.RawMessage + if err := d.Decode(&sl); err != nil { + return err + } + if sl != nil { + rv.Set(reflect.MakeSlice(rv.Type(), 0, 0)) + } + for _, item := range sl { + bv := reflect.New(rv.Type().Elem()) + if err := unmarshalJSONPb([]byte(item), bv.Interface()); err != nil { + return err + } + rv.Set(reflect.Append(rv, bv.Elem())) + } + return nil + } if _, ok := rv.Interface().(protoEnum); ok { var repr interface{} if err := d.Decode(&repr); err != nil { diff --git a/runtime/marshal_jsonpb_test.go b/runtime/marshal_jsonpb_test.go index 8d7d969d375..05f494827bf 100644 --- a/runtime/marshal_jsonpb_test.go +++ b/runtime/marshal_jsonpb_test.go @@ -7,16 +7,16 @@ import ( "strings" "testing" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/empty" + durationpb "github.com/golang/protobuf/ptypes/duration" + emptypb "github.com/golang/protobuf/ptypes/empty" structpb "github.com/golang/protobuf/ptypes/struct" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" + timestamppb "github.com/golang/protobuf/ptypes/timestamp" + wrapperspb "github.com/golang/protobuf/ptypes/wrappers" "github.com/google/go-cmp/cmp" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime/internal/examplepb" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/testing/protocmp" ) @@ -27,7 +27,7 @@ func TestJSONPbMarshal(t *testing.T) { MappedStringValue: map[string]string{}, MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, RepeatedEnumValue: []examplepb.NumericEnum{}, - TimestampValue: ×tamp.Timestamp{}, + TimestampValue: ×tamppb.Timestamp{}, Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { @@ -52,16 +52,13 @@ func TestJSONPbMarshal(t *testing.T) { } for i, spec := range []struct { - enumsAsInts, emitDefaults bool - indent string - origName bool - verifier func(json string) + useEnumNumbers, emitUnpopulated bool + indent string + useProtoNames bool + verifier func(json string) }{ { verifier: func(json string) { - if strings.ContainsAny(json, " \t\r\n") { - t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") - } if !strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = false; want true`, json) } @@ -71,7 +68,7 @@ func TestJSONPbMarshal(t *testing.T) { }, }, { - enumsAsInts: true, + useEnumNumbers: true, verifier: func(json string) { if strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) @@ -79,7 +76,7 @@ func TestJSONPbMarshal(t *testing.T) { }, }, { - emitDefaults: true, + emitUnpopulated: true, verifier: func(json string) { if want := `"sfixed32Value"`; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) @@ -95,7 +92,7 @@ func TestJSONPbMarshal(t *testing.T) { }, }, { - origName: true, + useProtoNames: true, verifier: func(json string) { if want := "uint64_value"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) @@ -105,10 +102,12 @@ func TestJSONPbMarshal(t *testing.T) { } { t.Run(strconv.Itoa(i), func(t *testing.T) { m := runtime.JSONPb{ - EnumsAsInts: spec.enumsAsInts, - EmitDefaults: spec.emitDefaults, - Indent: spec.indent, - OrigName: spec.origName, + MarshalOptions: protojson.MarshalOptions{ + EmitUnpopulated: spec.emitUnpopulated, + Indent: spec.indent, + UseProtoNames: spec.useProtoNames, + UseEnumNumbers: spec.useEnumNumbers, + }, } buf, err := m.Marshal(&msg) if err != nil { @@ -116,7 +115,8 @@ func TestJSONPbMarshal(t *testing.T) { } var got examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &got); err != nil { + unmarshaler := &protojson.UnmarshalOptions{} + if err = unmarshaler.Unmarshal(buf, &got); err != nil { t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", string(buf), err, spec) } if diff := cmp.Diff(&got, &msg, protocmp.Transform()); diff != "" { @@ -131,7 +131,7 @@ func TestJSONPbMarshal(t *testing.T) { func TestJSONPbMarshalFields(t *testing.T) { var m runtime.JSONPb - m.EnumsAsInts = true // builtin fixtures include an enum, expected to be marshaled as int + m.UseEnumNumbers = true // builtin fixtures include an enum, expected to be marshaled as int for _, spec := range builtinFieldFixtures { buf, err := m.Marshal(spec.data) if err != nil { @@ -142,7 +142,7 @@ func TestJSONPbMarshalFields(t *testing.T) { } } - m.EnumsAsInts = false + m.UseEnumNumbers = false buf, err := m.Marshal(examplepb.NumericEnum_ONE) if err != nil { t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) @@ -251,7 +251,7 @@ func TestJSONPbEncoder(t *testing.T) { MappedStringValue: map[string]string{}, MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, RepeatedEnumValue: []examplepb.NumericEnum{}, - TimestampValue: ×tamp.Timestamp{}, + TimestampValue: ×tamppb.Timestamp{}, Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { @@ -275,19 +275,13 @@ func TestJSONPbEncoder(t *testing.T) { } for i, spec := range []struct { - enumsAsInts, emitDefaults bool - indent string - origName bool - verifier func(json string) + useEnumNumbers, emitUnpopulated bool + indent string + useProtoNames bool + verifier func(json string) }{ { verifier: func(json string) { - // remove trailing delimiter before verifying - json = strings.TrimSuffix(json, "\n") - - if strings.ContainsAny(json, " \t\r\n") { - t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") - } if !strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = false; want true`, json) } @@ -297,7 +291,7 @@ func TestJSONPbEncoder(t *testing.T) { }, }, { - enumsAsInts: true, + useEnumNumbers: true, verifier: func(json string) { if strings.Contains(json, "ONE") { t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) @@ -305,7 +299,7 @@ func TestJSONPbEncoder(t *testing.T) { }, }, { - emitDefaults: true, + emitUnpopulated: true, verifier: func(json string) { if want := `"sfixed32Value"`; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) @@ -321,7 +315,7 @@ func TestJSONPbEncoder(t *testing.T) { }, }, { - origName: true, + useProtoNames: true, verifier: func(json string) { if want := "uint64_value"; !strings.Contains(json, want) { t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) @@ -330,10 +324,12 @@ func TestJSONPbEncoder(t *testing.T) { }, } { m := runtime.JSONPb{ - EnumsAsInts: spec.enumsAsInts, - EmitDefaults: spec.emitDefaults, - Indent: spec.indent, - OrigName: spec.origName, + MarshalOptions: protojson.MarshalOptions{ + EmitUnpopulated: spec.emitUnpopulated, + Indent: spec.indent, + UseProtoNames: spec.useProtoNames, + UseEnumNumbers: spec.useEnumNumbers, + }, } var buf bytes.Buffer @@ -343,7 +339,8 @@ func TestJSONPbEncoder(t *testing.T) { } var got examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(buf.String(), &got); err != nil { + unmarshaler := &protojson.UnmarshalOptions{} + if err := unmarshaler.Unmarshal(buf.Bytes(), &got); err != nil { t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", buf.String(), err, spec) } if diff := cmp.Diff(&got, &msg, protocmp.Transform()); diff != "" { @@ -368,7 +365,7 @@ func TestJSONPbEncoderFields(t *testing.T) { } } - m.EnumsAsInts = true + m.UseEnumNumbers = true buf, err := m.Marshal(examplepb.NumericEnum_ONE) if err != nil { t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) @@ -552,26 +549,23 @@ var ( json: `{"true":{"id":"foo"}}`, }, { - data: &duration.Duration{ + data: &durationpb.Duration{ Seconds: 123, Nanos: 456000000, }, json: `"123.456s"`, }, { - data: ×tamp.Timestamp{ + data: ×tamppb.Timestamp{ Seconds: 1462875553, Nanos: 123000000, }, json: `"2016-05-10T10:19:13.123Z"`, }, { - data: new(empty.Empty), + data: new(emptypb.Empty), json: "{}", }, - - // TODO(yugui) Enable unmarshaling of the following examples - // once jsonpb supports them. { data: &structpb.Value{ Kind: new(structpb.Value_NullValue), @@ -621,31 +615,31 @@ var ( }, { - data: &wrappers.BoolValue{Value: true}, + data: &wrapperspb.BoolValue{Value: true}, json: "true", }, { - data: &wrappers.DoubleValue{Value: 123.456}, + data: &wrapperspb.DoubleValue{Value: 123.456}, json: "123.456", }, { - data: &wrappers.FloatValue{Value: 123.456}, + data: &wrapperspb.FloatValue{Value: 123.456}, json: "123.456", }, { - data: &wrappers.Int32Value{Value: -123}, + data: &wrapperspb.Int32Value{Value: -123}, json: "-123", }, { - data: &wrappers.Int64Value{Value: -123}, + data: &wrapperspb.Int64Value{Value: -123}, json: `"-123"`, }, { - data: &wrappers.UInt32Value{Value: 123}, + data: &wrapperspb.UInt32Value{Value: 123}, json: "123", }, { - data: &wrappers.UInt64Value{Value: 123}, + data: &wrapperspb.UInt64Value{Value: 123}, json: `"123"`, }, // TODO(yugui) Add other well-known types once jsonpb supports them @@ -653,144 +647,210 @@ var ( ) func TestJSONPbMarshalResponseBodies(t *testing.T) { + marshaler := &runtime.JSONPb{} for i, spec := range []struct { - input interface{} - emitDefaults bool - verifier func(json string) + input interface{} + emitUnpopulated bool + verifier func(*testing.T, interface{}, []byte) }{ { input: &examplepb.ResponseBodyOut{ Response: &examplepb.ResponseBodyOut_Response{Data: "abcdef"}, }, - verifier: func(json string) { - expected := `{"response":{"data":"abcdef"}}` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out examplepb.ResponseBodyOut + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, &out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { - emitDefaults: true, - input: &examplepb.ResponseBodyOut{}, - verifier: func(json string) { - expected := `{"response":null}` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + emitUnpopulated: true, + input: &examplepb.ResponseBodyOut{}, + verifier: func(t *testing.T, input interface{}, json []byte) { + var out examplepb.ResponseBodyOut + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, &out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { input: &examplepb.RepeatedResponseBodyOut_Response{}, - verifier: func(json string) { - expected := `{}` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out examplepb.RepeatedResponseBodyOut_Response + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, &out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { - emitDefaults: true, - input: &examplepb.RepeatedResponseBodyOut_Response{}, - verifier: func(json string) { - expected := `{"data":"","type":"UNKNOWN"}` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + emitUnpopulated: true, + input: &examplepb.RepeatedResponseBodyOut_Response{}, + verifier: func(t *testing.T, input interface{}, json []byte) { + var out examplepb.RepeatedResponseBodyOut_Response + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, &out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { input: ([]*examplepb.RepeatedResponseBodyOut_Response)(nil), - verifier: func(json string) { - expected := `null` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out []*examplepb.RepeatedResponseBodyOut_Response + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { - emitDefaults: true, - input: ([]*examplepb.RepeatedResponseBodyOut_Response)(nil), - verifier: func(json string) { - expected := `[]` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + emitUnpopulated: true, + input: ([]*examplepb.RepeatedResponseBodyOut_Response)(nil), + verifier: func(t *testing.T, _ interface{}, json []byte) { + var out []*examplepb.RepeatedResponseBodyOut_Response + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff([]*examplepb.RepeatedResponseBodyOut_Response{}, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { input: []*examplepb.RepeatedResponseBodyOut_Response{}, - verifier: func(json string) { - expected := `[]` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out []*examplepb.RepeatedResponseBodyOut_Response + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { input: []string{"something"}, - verifier: func(json string) { - expected := `["something"]` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out []string + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { input: []string{}, - verifier: func(json string) { - expected := `[]` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out []string + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { input: ([]string)(nil), - verifier: func(json string) { - expected := `null` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out []string + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { - emitDefaults: true, - input: ([]string)(nil), - verifier: func(json string) { - expected := `[]` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + emitUnpopulated: true, + input: ([]string)(nil), + verifier: func(t *testing.T, _ interface{}, json []byte) { + var out []string + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff([]string{}, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { input: []*examplepb.RepeatedResponseBodyOut_Response{ - &examplepb.RepeatedResponseBodyOut_Response{}, - &examplepb.RepeatedResponseBodyOut_Response{ + {}, + { Data: "abc", Type: examplepb.RepeatedResponseBodyOut_Response_A, }, }, - verifier: func(json string) { - expected := `[{},{"data":"abc","type":"A"}]` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out []*examplepb.RepeatedResponseBodyOut_Response + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, { - emitDefaults: true, + emitUnpopulated: true, input: []*examplepb.RepeatedResponseBodyOut_Response{ - &examplepb.RepeatedResponseBodyOut_Response{}, - &examplepb.RepeatedResponseBodyOut_Response{ + {}, + { Data: "abc", Type: examplepb.RepeatedResponseBodyOut_Response_B, }, }, - verifier: func(json string) { - expected := `[{"data":"","type":"UNKNOWN"},{"data":"abc","type":"B"}]` - if json != expected { - t.Errorf("json not equal (%q, %q)", json, expected) + verifier: func(t *testing.T, input interface{}, json []byte) { + var out []*examplepb.RepeatedResponseBodyOut_Response + err := marshaler.Unmarshal(json, &out) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + diff := cmp.Diff(input, out, protocmp.Transform()) + if diff != "" { + t.Errorf("json not equal:\n%s", diff) } }, }, @@ -798,7 +858,9 @@ func TestJSONPbMarshalResponseBodies(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { m := runtime.JSONPb{ - EmitDefaults: spec.emitDefaults, + MarshalOptions: protojson.MarshalOptions{ + EmitUnpopulated: spec.emitUnpopulated, + }, } val := spec.input buf, err := m.Marshal(val) @@ -806,7 +868,7 @@ func TestJSONPbMarshalResponseBodies(t *testing.T) { t.Errorf("m.Marshal(%v) failed with %v; want success; spec=%v", val, err, spec) } if spec.verifier != nil { - spec.verifier(string(buf)) + spec.verifier(t, spec.input, buf) } }) } diff --git a/runtime/marshal_proto.go b/runtime/marshal_proto.go index f65d1a2676b..69eeecc9224 100644 --- a/runtime/marshal_proto.go +++ b/runtime/marshal_proto.go @@ -4,8 +4,9 @@ import ( "io" "errors" - "github.com/golang/protobuf/proto" "io/ioutil" + + "google.golang.org/protobuf/proto" ) // ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes diff --git a/runtime/marshal_proto_test.go b/runtime/marshal_proto_test.go index 131918c12d8..df156ac0b16 100644 --- a/runtime/marshal_proto_test.go +++ b/runtime/marshal_proto_test.go @@ -4,10 +4,10 @@ import ( "bytes" "testing" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/timestamp" + timestamppb "github.com/golang/protobuf/ptypes/timestamp" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime/internal/examplepb" + "google.golang.org/protobuf/proto" ) var message = &examplepb.ABitOfEverything{ @@ -16,7 +16,7 @@ var message = &examplepb.ABitOfEverything{ MappedStringValue: nil, MappedNestedValue: nil, RepeatedEnumValue: nil, - TimestampValue: ×tamp.Timestamp{}, + TimestampValue: ×tamppb.Timestamp{}, Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", Nested: []*examplepb.ABitOfEverything_Nested{ { diff --git a/runtime/marshaler_registry.go b/runtime/marshaler_registry.go index 5cc53ae4f68..146b34a7dae 100644 --- a/runtime/marshaler_registry.go +++ b/runtime/marshaler_registry.go @@ -3,6 +3,8 @@ package runtime import ( "errors" "net/http" + + "google.golang.org/protobuf/encoding/protojson" ) // MIMEWildcard is the fallback MIME type used for requests which do not match @@ -13,7 +15,14 @@ var ( acceptHeader = http.CanonicalHeaderKey("Accept") contentTypeHeader = http.CanonicalHeaderKey("Content-Type") - defaultMarshaler = &JSONPb{OrigName: true} + defaultMarshaler = &JSONPb{ + MarshalOptions: protojson.MarshalOptions{ + // TODO(johanbrandhorst): Change this to true before v2 + EmitUnpopulated: false, + // TODO(johanbrandhorst): Change this to false before v2 + UseProtoNames: true, + }, + } ) // MarshalerForRequest returns the inbound/outbound marshalers for this request. diff --git a/runtime/mux.go b/runtime/mux.go index 70caae1dade..b33bf47d7d5 100644 --- a/runtime/mux.go +++ b/runtime/mux.go @@ -7,10 +7,10 @@ import ( "net/textproto" "strings" - "github.com/golang/protobuf/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // A HandlerFunc handles a specific pair of path pattern and HTTP method. diff --git a/runtime/proto2_convert.go b/runtime/proto2_convert.go index a3151e2a552..d549407f20f 100644 --- a/runtime/proto2_convert.go +++ b/runtime/proto2_convert.go @@ -1,7 +1,7 @@ package runtime import ( - "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/proto" ) // StringP returns a pointer to a string whose pointee is same as the given string value. diff --git a/runtime/query.go b/runtime/query.go index 61cae533557..aab332ae56c 100644 --- a/runtime/query.go +++ b/runtime/query.go @@ -11,7 +11,7 @@ import ( "time" "github.com/golang/protobuf/ptypes" - "github.com/golang/protobuf/ptypes/wrappers" + wrapperspb "github.com/golang/protobuf/ptypes/wrappers" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "google.golang.org/genproto/protobuf/field_mask" "google.golang.org/grpc/grpclog" @@ -274,51 +274,51 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.DoubleValue{Value: v} + msg = &wrapperspb.DoubleValue{Value: v} case "google.protobuf.FloatValue": v, err := strconv.ParseFloat(value, 32) if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.FloatValue{Value: float32(v)} + msg = &wrapperspb.FloatValue{Value: float32(v)} case "google.protobuf.Int64Value": v, err := strconv.ParseInt(value, 10, 64) if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.Int64Value{Value: v} + msg = &wrapperspb.Int64Value{Value: v} case "google.protobuf.Int32Value": v, err := strconv.ParseInt(value, 10, 32) if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.Int32Value{Value: int32(v)} + msg = &wrapperspb.Int32Value{Value: int32(v)} case "google.protobuf.UInt64Value": v, err := strconv.ParseUint(value, 10, 64) if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.UInt64Value{Value: v} + msg = &wrapperspb.UInt64Value{Value: v} case "google.protobuf.UInt32Value": v, err := strconv.ParseUint(value, 10, 32) if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.UInt32Value{Value: uint32(v)} + msg = &wrapperspb.UInt32Value{Value: uint32(v)} case "google.protobuf.BoolValue": v, err := strconv.ParseBool(value) if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.BoolValue{Value: v} + msg = &wrapperspb.BoolValue{Value: v} case "google.protobuf.StringValue": - msg = &wrappers.StringValue{Value: value} + msg = &wrapperspb.StringValue{Value: value} case "google.protobuf.BytesValue": v, err := base64.StdEncoding.DecodeString(value) if err != nil { return protoreflect.Value{}, err } - msg = &wrappers.BytesValue{Value: v} + msg = &wrapperspb.BytesValue{Value: v} case "google.protobuf.FieldMask": fm := &field_mask.FieldMask{} for _, v := range strings.Split(value, ",") { diff --git a/runtime/query_test.go b/runtime/query_test.go index 8c7e68af720..c7ded11eb97 100644 --- a/runtime/query_test.go +++ b/runtime/query_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/golang/protobuf/ptypes" - "github.com/golang/protobuf/ptypes/wrappers" + wrapperspb "github.com/golang/protobuf/ptypes/wrappers" "github.com/google/go-cmp/cmp" "github.com/grpc-ecosystem/grpc-gateway/v2/internal/utilities" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -163,21 +163,21 @@ func TestPopulateParameters(t *testing.T) { StringValue: "str", BytesValue: []byte("bytes"), RepeatedValue: []string{"a", "b", "c"}, - RepeatedMessage: []*wrappers.UInt64Value{{Value: 1}, {Value: 2}, {Value: 3}}, + RepeatedMessage: []*wrapperspb.UInt64Value{{Value: 1}, {Value: 2}, {Value: 3}}, EnumValue: examplepb.EnumValue_Y, RepeatedEnum: []examplepb.EnumValue{examplepb.EnumValue_Y, examplepb.EnumValue_Z, examplepb.EnumValue_X}, TimestampValue: timePb, DurationValue: durationPb, FieldmaskValue: fieldmaskPb, - WrapperFloatValue: &wrappers.FloatValue{Value: 1.5}, - WrapperDoubleValue: &wrappers.DoubleValue{Value: 2.5}, - WrapperInt64Value: &wrappers.Int64Value{Value: -1}, - WrapperInt32Value: &wrappers.Int32Value{Value: -2}, - WrapperUInt64Value: &wrappers.UInt64Value{Value: 3}, - WrapperUInt32Value: &wrappers.UInt32Value{Value: 4}, - WrapperBoolValue: &wrappers.BoolValue{Value: true}, - WrapperStringValue: &wrappers.StringValue{Value: "str"}, - WrapperBytesValue: &wrappers.BytesValue{Value: []byte("bytes")}, + WrapperFloatValue: &wrapperspb.FloatValue{Value: 1.5}, + WrapperDoubleValue: &wrapperspb.DoubleValue{Value: 2.5}, + WrapperInt64Value: &wrapperspb.Int64Value{Value: -1}, + WrapperInt32Value: &wrapperspb.Int32Value{Value: -2}, + WrapperUInt64Value: &wrapperspb.UInt64Value{Value: 3}, + WrapperUInt32Value: &wrapperspb.UInt32Value{Value: 4}, + WrapperBoolValue: &wrapperspb.BoolValue{Value: true}, + WrapperStringValue: &wrapperspb.StringValue{Value: "str"}, + WrapperBytesValue: &wrapperspb.BytesValue{Value: []byte("bytes")}, MapValue: map[string]string{ "key": "value", "second": "bar", @@ -197,7 +197,7 @@ func TestPopulateParameters(t *testing.T) { MapValue12: map[string]float64{"key": 2.5}, MapValue14: map[string]bool{"key": true}, MapValue15: map[bool]string{true: "value"}, - MapValue16: map[string]*wrappers.UInt64Value{"key": {Value: 2}}, + MapValue16: map[string]*wrapperspb.UInt64Value{"key": {Value: 2}}, }, }, { @@ -244,15 +244,15 @@ func TestPopulateParameters(t *testing.T) { TimestampValue: timePb, DurationValue: durationPb, FieldmaskValue: fieldmaskPb, - WrapperFloatValue: &wrappers.FloatValue{Value: 1.5}, - WrapperDoubleValue: &wrappers.DoubleValue{Value: 2.5}, - WrapperInt64Value: &wrappers.Int64Value{Value: -1}, - WrapperInt32Value: &wrappers.Int32Value{Value: -2}, - WrapperUInt64Value: &wrappers.UInt64Value{Value: 3}, - WrapperUInt32Value: &wrappers.UInt32Value{Value: 4}, - WrapperBoolValue: &wrappers.BoolValue{Value: true}, - WrapperStringValue: &wrappers.StringValue{Value: "str"}, - WrapperBytesValue: &wrappers.BytesValue{Value: []byte("bytes")}, + WrapperFloatValue: &wrapperspb.FloatValue{Value: 1.5}, + WrapperDoubleValue: &wrapperspb.DoubleValue{Value: 2.5}, + WrapperInt64Value: &wrapperspb.Int64Value{Value: -1}, + WrapperInt32Value: &wrapperspb.Int32Value{Value: -2}, + WrapperUInt64Value: &wrapperspb.UInt64Value{Value: 3}, + WrapperUInt32Value: &wrapperspb.UInt32Value{Value: 4}, + WrapperBoolValue: &wrapperspb.BoolValue{Value: true}, + WrapperStringValue: &wrapperspb.StringValue{Value: "str"}, + WrapperBytesValue: &wrapperspb.BytesValue{Value: []byte("bytes")}, }, }, {