Cli to generate protocol buffers

at_ishikawa
2 min readMay 4, 2018

--

This article is about generating binary from cli, and not about what protocol buffers are.

If you want to know, you should see official documentation: https://developers.google.com/protocol-buffers/docs/overview

Getting Started

Install a compiler for protocol buffer by homebrew first.

$ brew install protobuf
$ protoc --version
libprotoc 3.5.1

Prepare a proto file

$ cat protos/main.proto
syntax = "proto3";
message Html {
enum Type {
NO_TYPE = 0;
HTML5 = 1;
XHTML = 2;
}
Type type = 1;
string head = 2;
Body body = 3;
}
message Body {
string header = 1;
repeated string main = 2;
string footer = 3;
}

Protoc cli usage

  • Generate a code from a proto file
$ protoc --php_out=php protos/main.proto
$ ls php
Body.php GPBMetadata Html.php Html_Type.php
  • Generate a binary by protoc with an encode option
$ cat proto.text
type: HTML5
head: "css"
body: {
header: "header"
main: "main"
main: "main2"
footer: "footer"
}
$ protoc --encode=Html protos/main.proto < proto.text > binary.data
$ hexdump -C binary.data
00000000 08 01 12 03 63 73 73 1a 1d 0a 06 68 65 61 64 65 |....css....heade|
00000010 72 12 04 6d 61 69 6e 12 05 6d 61 69 6e 32 1a 06 |r..main..main2..|
00000020 66 6f 6f 74 65 72 |footer|
00000026$
  • Unserialize from binary by protoc with decode option
$ protoc --decode Html protos/main.proto < binary.data
type: HTML5
head: "css"
body {
header: "header"
main: "main"
main: "main2"
footer: "footer"
}

Reference

  • To use protocol buffers
  • The home brew repository for protocol buffers
  • GitHub Issue: Use json format to decode by protoc

--

--