pbgo基于 Protobuf 的 RPC/REST 迷你框架
pbgo 基于 Protobuf 定義接口規(guī)范,通過(guò)pbgo提供的插件生成RPC和REST相關(guān)代碼。
創(chuàng)建hello.proto文件,定義接口規(guī)范:
syntax = "proto3";
package hello_pb;
import "github.com/chai2010/pbgo/pbgo.proto";
message String {
string value = 1;
}
service EchoService {
rpc Echo (String) returns (String) {
option (pbgo.rest_api) = {
get: "/echo/:value"
};
}
}
用pbgo插件生成代碼:
$ protoc -I=. -I=$(GOPATH)/src --pbgo_out=. hello.proto
創(chuàng)建REST服務(wù):
type EchoService struct{}
func (p *EchoService) Echo(request *hello_pb.String, reply *hello_pb.String) error {
*reply = *request
return nil
}
func main() {
router := hello_pb.EchoServiceHandler(new(EchoService))
log.Fatal(http.ListenAndServe(":8080", router))
}
測(cè)試REST服務(wù):
$ curl localhost:8080/echo/gopher
{"value":"gopher"}
$ curl localhost:8080/echo/gopher?value=cgo
{"value":"cgo"}
詳細(xì)的例子請(qǐng)參考:https://github.com/chai2010/pbgo/blob/master/examples/hello.p
評(píng)論
圖片
表情
