0
0

GoでgRPCサーバーを立ててみる2(gRPCのスキーマ定義とコード生成)

Posted at

こんにちは。
金です。
今日は「gRPCのスキーマ定義」について部分いたします。

事前準備

まずは、以下のようにディレクトリとファイルを作成します。

.
└─ article
   ├── client ─ client.go
   ├── repository ─ repository.go
   ├── server ─ server.go
   ├── service - service.go
   └── article.proto

また、ルート配下でgo moduleの初期化を行なっておきましょう。

go mod init

.protoファイルの記述

.protoファイルにgRPCのスキーマ定義を記述していきます。
実装するarticleサービスの仕様はprotoファイルのservice部分で定義しているように、CRUD+全取得ができるものになっています。

article/article.proto
syntax = "proto3";

package article;
option go_package = "article/pb";

// やり取りする記事の型定義
message Article {
    int64 id = 1;
    string author = 2;
    string title = 3;
    string content = 4;
}

// CREATEとUPDATEにおける入力のための型
message ArticleInput {
    string author = 1;
    string title = 2;
    string content = 3;
}

// CREATEする記事の内容(author, title, content)を受け取る
message CreateArticleRequest {
    ArticleInput articleInput = 1;
}

// CREATEした記事を返す
message CreateArticleResponse {
    Article article = 1;
}

// READする記事のIDを受け取る
message ReadArticleRequest {
    int64 id = 1;
}

// 該当するIDの記事を返す
message ReadArticleResponse {
    Article article = 1;
}

// UPDATEする記事のIDと変更内容を受け取る
message UpdateArticleRequest {
    int64 id = 1;
    ArticleInput articleInput = 2;
}

// UPDATEした記事を返す 
message UpdateArticleResponse {
    Article article = 1;
}

// DELETEする記事のIDを受け取る
message DeleteArticleResponse {
    int64 id = 1;
}

// DELETEした記事のIDを返す
message DeleteArticleRequest {
    int64 id = 1;
}

// 全取得の際、入力は無し
message ListArticleRequest {

}

// 全取得した記事を1つずつ返すので、配列(repeated)の形ではなくArticle1つを返す形
message ListArticleResponse {
    Article article = 1;
}

// articleサービスを定義
service ArticleService {
    rpc CreateArticle(CreateArticleRequest) returns(CreateArticleResponse);
    rpc ReadArticle(ReadArticleRequest) returns(ReadArticleResponse);
    rpc UpdateArticle(UpdateArticleRequest) returns(UpdateArticleResponse);
    rpc DeleteArticle(DeleteArticleRequest) returns(DeleteArticleResponse);
    rpc ListArticle(ListArticleRequest) returns(stream ListArticleResponse);
}

全取得のみ、1リクエストに対して複数レスポンスを返すServer Streaming仕様です。

コード生成

記述したprotoファイルをもとに自動生成を行います。

protobufをインストールしていない場合は事前にインストールしましょう。

brew install protobuf

また、Goでprotocコマンドを使うために必要なプラグインも入れておきましょう。

go get -u google.golang.org/grpc \
	  github.com/golang/protobuf/protoc-gen-go

最後にPATHの更新を行います。

protoc ./article/article.proto --go_out=plugins=grpc:.

articleディレクトリ配下にpbディレクトリが作成され、その中に自動生成されたarticle.pb.goが確認できるはずです。

.
└─ article
   ├── client ─ client.go
   ├── pb ─ article.pb.go (新しく生成されたファイル)
   ├── repository ─ repository.go
   ├── server ─ server.go
   ├── service - service.go
   └── article.proto
0
0
0

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
0
0