12
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

protocolBuffersでgoogle/protobufをimportする方法

Last updated at Posted at 2019-08-12

grpc-webを使っているともうなかなかRESTには戻れない@kkkkkです。

今回はprotocol buffersの定義で結構便利な
https://github.com/protocolbuffers/protobuf
についてimportする方法を紹介します。

色々やり方はあると思いますが、
git submodulesでvendorとしてimportするのが楽かなと思ってます(他に良い方法あったら教えて下さい)。

vendorにgit submodulesをaddする

$ tree -L 2                                                                                                                                                                                                  
.
├── articles
│   └── show.proto
├── helloworld.proto
└── vendor
    └── protobuf

3 directories, 2 files

の状態になるようにします。

mkdir vendor
cd vendor
git submodule add https://github.com/protocolbuffers/protobuf.git

これでvendor作成!

protocでprotobuffers/protobufのimport方法

例は適当なメディアの記事詳細APIとかのイメージです。

articles/show.proto

syntax = "proto3";

import "google/protobuf/timestamp.proto";

package articles;

service ArticleService {
  rpc Show(ShowArticleRequest) returns (ShowArticleResponse);
}

message ShowArticleRequest {
  int64 id = 1;
}

message ShowArticleResponse {
  int64 id = 1;
  string title = 2;
  string description = 3;
  string contents = 4;
  string img_url = 5;
  int64 category_id = 6;
  string keywords = 7;
  google.protobuf.Timestamp created_at = 8;
}

で作成。

import "google/protobuf/timestamp.proto";

でimportして

google.protobuf.Timestamp created_at = 8;

で宣言します。

上記のrootディレクトリで以下実行。

#!/bin/sh

SERVER_OUTPUT_DIR=outputdir

mkdir -p ${CLIENT_OUTDIR} ${SERVER_OUTPUT_DIR}

protoc --proto_path=. --proto_path=vendor/protobuf/src articles/show.proto \
    --go_out=plugins=grpc:${SERVER_OUTPUT_DIR}
-Ivendor/protobuf/src

protocコマンド実行時にprotobuf/srcをimportすること!

gRPC良いね!

12
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?