protobuf-elixir

Hex.pmBuild Status

A pure Elixir implementation of Google Protobuf

Why this instead of exprotobuf(gpb)?

It have some must-have and other cool features like:

  1. A protoc plugin to generate Elixir code just like what other official libs do, which is powerful and reliable.
  2. Generate simple and explicit code with the power of Macro. (see test/support/test_msg.ex)
  3. Plugins support. Only grpc is supported now.
  4. Use structs for messages instead of Erlang records.
  5. Support Typespec in generated code.

Installation

The package can be installed by adding protobuf to your list of dependencies in mix.exs:

def deps do
  [{:protobuf, "~> 0.3.1"}]
end

Features

Usage

Generate Elixir code

  1. Install protochere
  2. Install protoc plugin protoc-gen-elixir for Elixir . NOTE: You have to make sure protoc-gen-elixir(this name is important) is in your PATH.
    $ mix escript.install hex protobuf
  3. Generate Elixir code using protoc
    $ protoc --elixir_out=./lib foo.proto
  4. Files foo.pb.ex will be generated, like:
defmodule Foo.Bar do
  use Protobuf

  defstruct [:a, :b]

  field :a, 1, optional: true, type: :int32
  field :b, 2, optional: true, type: :string
end

defmodule Foo do
  use Protobuf

  defstruct [:a, :b, :c]

  field :a, 1, required: true, type: :float
  field :b, 2, optional: true, type: :fixed64, default: 5
  field :e, 3, optional: true, type: Foo.Bar
end

Encode and decode in your code

struct = Foo.new(a: 3.2, c: Foo.Bar.new())
encoded = Foo.encode(struct)
struct = Foo.decode(encoded)

Note:

gRPC Support

If you write services in protobuf, you can generate gRPC code by passing plugins=grpc in --go_out:

$ protoc --elixir_out=plugins=grpc:./lib/ *.proto

Tips for protoc

Acknowledgements

Many thanks to gpb and golang/protobuf as good examples of writing Protobuf decoder/encoder.