onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
677 stars 33 forks source link

How to generate grpc protobuf files #197

Open onmyway133 opened 5 years ago

onmyway133 commented 5 years ago

protoc

https://grpc.io/docs/quickstart/go.html

Install the protoc compiler that is used to generate gRPC service code. The simplest way to do this is to download pre-compiled binaries for your platform(protoc--.zip) from here: https://github.com/google/protobuf/releases

Unzip this file. Update the environment variable PATH to include the path to the protoc binary file.

Go protoc plugin

https://github.com/golang/protobuf

go get -u github.com/golang/protobuf/protoc-gen-go
export PATH=$PATH:$GOPATH/bin
source ~/.zshrc

Swift protoc plugin

https://github.com/grpc/grpc-swift

The recommended way to use Swift gRPC is to first define an API using the Protocol Buffer language and then use the Protocol Buffer Compiler and the Swift Protobuf and Swift gRPC plugins to generate the necessary support code.

git clone https://github.com/grpc/grpc-swift.git
cd grpc-swift
make
sudo cp protoc-gen-swift protoc-gen-swiftgrpc /usr/local/bin

Generate

protoc --swift_out=MyApp/Api --swiftgrpc_out=Client=true,Server=false:MyApp/Api --go_out=plugins=grpc:server/api api.proto

In case we need to cd

cd MyApp/Library/Models/Proto

protoc --swift_out=../Generated --swiftgrpc_out=Client=true,Server=false:../Generated api.proto

Empty

If remote import is needed, then the workaround is to download the that proto locally, for example empty.proto https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/empty.proto

Inside SwiftProtobuf pod, there is generated empty.pb.swift

public struct Google_Protobuf_Empty {
  // SwiftProtobuf.Message conformance is added in an extension below. See the
  // `Message` and `Message+*Additions` files in the SwiftProtobuf library for
  // methods supported on all messages.

  public var unknownFields = SwiftProtobuf.UnknownStorage()

  public init() {}
}

To consume, we can

import SwiftProtobuf

let empty = Google_Protobuf_Empty()

oneof mode

message Person {
  oneof mode {
    Human human = 1;
    Superman superman = 2;
  }
}

Cannot convert value of type 'Server_Person.OneOf_Mode' to expected argument type 'Server_Human'

Need to assign the mode

var person = Person()
person.mode = Person.OneOf_Mode.Human()
onmyway133 commented 5 years ago

Read more