Go語言: 產生Protobuf的Service介面

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Protobuf 是Google發布的開源編碼規範, 官方支援C++/Java/Python等幾種語言.

Go語言發布之後, Go的官方團隊發布的GoProtobuf也實現了Protobuf支援.

不過GoProtobuf官方版本並沒有實現rpc的支援.
protoc-gen-go 甚至連 service 的介面也未產生.

如果看過 “JSON-RPC: a tale of interfaces” 文章, 會發現Go語言支援rpc非常容易.

我們現在就開始嘗試給GoProtobuf增加rpc的支援.

當然, 第一步是要產生Service介面.

建立 service.go 檔案:

// Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package generator// ServicePlugin produce the Service interface.type ServicePlugin struct {    *Generator}// Name returns the name of the plugin.func (p *ServicePlugin) Name() string { return "ServiceInterface" }// Init is called once after data structures are built but before// code generation begins.func (p *ServicePlugin) Init(g *Generator) {    p.Generator = g}// Generate produces the code generated by the plugin for this file.func (p *ServicePlugin) GenerateImports(file *FileDescriptor) {    //}// Generate generates the Service interface.func (p *ServicePlugin) Generate(file *FileDescriptor) {    for _, svc := range file.Service {        name := CamelCase(*svc.Name)        p.P("type ", name, " interface {")        p.In()        for _, m := range svc.Method {            method := CamelCase(*m.Name)            iType := p.ObjectNamed(*m.InputType)            oType := p.ObjectNamed(*m.OutputType)            p.P(method, "(in *", p.TypeName(iType), ", out *", p.TypeName(oType), ") error")        }        p.Out()        p.P("}")    }}func init() {    RegisterPlugin(new(ServicePlugin))}

將 service.go 檔案放到 code.google.com/p/goprotobuf/protoc-gen-go/generator 目錄.
重新編譯安裝 code.google.com/p/goprotobuf/protoc-gen-go.

建立 echo.proto 檔案:

// Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package echo;option cc_generic_services = true;option java_generic_services = true;option py_generic_services = true;message EchoRequest {    required string message = 1;}message EchoResponse {    required string message = 1;}service EchoService {    rpc echo (EchoRequest) returns (EchoResponse);}

編譯 echo.proto 檔案:

protoc --go_out=. echo.proto

產生 echo.pb.go 檔案:

// Code generated by protoc-gen-go.// source: echo.proto// DO NOT EDIT!package echoimport proto "code.google.com/p/goprotobuf/proto"import json "encoding/json"import math "math"// Reference proto, json, and math imports to suppress error if they are not otherwise used.var _ = proto.Marshalvar _ = &json.SyntaxError{}var _ = math.Inftype EchoRequest struct {    Message          *string `protobuf:"bytes,1,req,name=message" json:"message,omitempty"`    XXX_unrecognized []byte  `json:"-"`}func (m *EchoRequest) Reset()         { *m = EchoRequest{} }func (m *EchoRequest) String() string { return proto.CompactTextString(m) }func (*EchoRequest) ProtoMessage()    {}func (m *EchoRequest) GetMessage() string {    if m != nil && m.Message != nil {        return *m.Message    }    return ""}type EchoResponse struct {    Message          *string `protobuf:"bytes,1,req,name=message" json:"message,omitempty"`    XXX_unrecognized []byte  `json:"-"`}func (m *EchoResponse) Reset()         { *m = EchoResponse{} }func (m *EchoResponse) String() string { return proto.CompactTextString(m) }func (*EchoResponse) ProtoMessage()    {}func (m *EchoResponse) GetMessage() string {    if m != nil && m.Message != nil {        return *m.Message    }    return ""}func init() {}type EchoService interface {    Echo(in *EchoRequest, out *EchoResponse) error}

注意最後的介面部分是由我們添加的 service.go 產生的:

type EchoService interface {    Echo(in *EchoRequest, out *EchoResponse) error}

最基本的準備工作已經完成, 下面就是參考JSON-RPC的例子, 實現一個protobuf版本的rpc了.

下次繼續…

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.