Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)
go_binary(
name = "protoc-gen-bm",
embed = [":go_default_library"],
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
importpath = "go-common/app/tool/protoc-gen-bm",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/tool/protoc-gen-bm/codegenerator:go_default_library",
"//app/tool/protoc-gen-bm/genbm:go_default_library",
"//app/tool/protoc-gen-bm/util:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/tool/protoc-gen-bm/codegenerator:all-srcs",
"//app/tool/protoc-gen-bm/genbm:all-srcs",
"//app/tool/protoc-gen-bm/generator:all-srcs",
"//app/tool/protoc-gen-bm/jsonpb:all-srcs",
"//app/tool/protoc-gen-bm/util:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,4 @@
#### Version 0.0.2
1. 可选使用 jsonpb 代替 encoding/json NOTE: jsonpb 很慢
#### Version 0.0.1
1. init 支持从 google.api.http 生成 bm server 代码

View File

@@ -0,0 +1,7 @@
# Owner
weicheng
# Author
weicheng
# Reviewer

View File

@@ -0,0 +1,21 @@
GOFILES=$(shell find . -name "*.go" -type f)
EXAMPLE_HELLOWORLD_DIR=examples/helloworld
PROTO_FILE=$(EXAMPLE_HELLOWORLD_DIR)/api/helloworld.proto
VENDOR_DIR=$(shell echo $$GOPATH | cut -d':' -f1)/src/go-common/vendor
protoc-gen-bm: $(GOFILES)
go install .
protoc-gen-go: $(PROTO_FILE)
protoc -I. -I$(VENDOR_DIR) --go_out=plugins=grpc:. $<
examples-helloworld: $(PROTO_FILE) protoc-gen-bm protoc-gen-go
protoc -I. -I$(VENDOR_DIR) --bm_out=logtostderr=1,v=10:. $<
examples-helloworld-jsonpb: $(PROTO_FILE) protoc-gen-bm protoc-gen-go
protoc -I. -I$(VENDOR_DIR) --bm_out=logtostderr=1,v=10,jsonpb=true:. $<
test:
go test ./...
.PHONY: protoc-gen-bm protoc-gen-go examples-helloworld test

View File

@@ -0,0 +1,6 @@
# See the OWNERS docs at https://go.k8s.io/owners
labels:
- tool
options:
no_parent_owners: true

View File

@@ -0,0 +1,196 @@
# Deprecated: 请大佬移步 [https://git.bilibili.co/platform/go-common/tree/master/app/tool/bmproto](https://git.bilibili.co/platform/go-common/tree/master/app/tool/bmproto) 生成的代码不一样但是功能一致, 可以无缝迁移!
# protoc-gen-bm
通过 protobuf 自动生成 bm server统一数据传输模型.
### 安装
```bash
go install go-common/app/tool/protoc-gen-bm
```
### 如何生成 bm server 代码 example
```bash
# 生成 examples/helloworld bm server 代码
protoc -I. -Ithird_party/googleapis --bm_out=:. examples/helloworld/api/v1/helloworld.proto
# 使用 jsonpb
protoc -I. -Ithird_party/googleapis --bm_out=jsonpb=true:. examples/helloworld/api/v1/helloworld.proto
```
### 给 protobuf 添加 http 描述示例
```protobuf
service Messaging {
rpc GetMessage(GetMessageRequest) returns (Message) {
option (google.api.http) = {
get: "/message";
};
}
}
message GetMessageRequest {
string name = 1; // Mapped to URL path.
}
message Message {
string text = 1; // The resource content.
}
```
http 到 gRPC 的映射如下
| HTTP | gRPC |
|-------------------------|---------------------------|
| `GET /message?name=foo` | `GetMessage(name: "foo")` |
对于 GET 之类不包含 Body 的请求,所有的 Request Message 将被映射到 URL Query 中。
对于嵌套的字段通过 `.` 分割 例如:
```protobuf
service Messaging {
rpc GetMessage(GetMessageRequest) returns (Message) {
option (google.api.http) = {
get:"/messages"
};
}
}
message GetMessageRequest {
message SubMessage {
string subfield = 1;
}
string message_id = 1;
int64 revision = 2;
SubMessage sub = 3;
}
```
| HTTP | gRPC |
|---------------------------------------------------------------|---------------------------------------------------------------------------------|
| `GET /messages?message_id=123456&revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))` |
对于包含 Body 的 http 请求body 字段可以用来指定数据映射
```protobuf
service Messaging {
rpc CreateMessage(CreateMessageRequest) returns (Message) {
option (google.api.http) = {
post: "/messages"
body: "*"
};
}
}
message CreateMessageRequest {
string message_id = 1;
string text = 2;
}
```
| HTTP | gRPC |
|--------------------------------------------------------------|----------------------------------------------------|
| `POST /v1/messages {"message_id": "123456", "text": "Hi!" }` | `CreateMessage(message_id: "123456", text: "Hi!")` |
### Response 响应
Json Response
```json
{
"code": 0,
"message": "this is message",
"data": {// Response Message Marshal as JSON}
}
```
Protobuf Response
```protobuf
message PB {
int64 Code = 1;
string Message = 2;
uint64 TTL = 3;
google.protobuf.Any Data = 4;
}
```
### 与 google.api.http 不一致的地方
- 因为 bm 不支持 restful 格式 API所以不支持映射参数到 Path
- Response 多了层包装,而不是直接返回 message 主体message 主体被放到 data 中
### 注意事项
#### bazel 编译问题
目前自动生成的 BUILD 的文件无法正常编译,需要手动修改,以 example/helloworld 项目为例,需要对 BUILD 文件进行以下修改
```diff
--- a/app/tool/protoc-gen-bm/examples/helloworld/api/v1/BUILD
+++ b/app/tool/protoc-gen-bm/examples/helloworld/api/v1/BUILD
@@ -13,8 +13,8 @@ load(
proto_library(
name = "v1_proto",
srcs = ["helloworld.proto"],
- tags = ["automanaged"],
- deps = ["google/api/annotations.proto"],
+ tags = ["manual"],
+ deps = ["@go_googleapis//google/api:annotations_proto"],
)
go_proto_library(
@@ -22,14 +22,14 @@ go_proto_library(
compilers = ["@io_bazel_rules_go//proto:go_grpc"],
importpath = "go-common/app/tool/protoc-gen-bm/examples/helloworld/api/v1",
proto = ":v1_proto",
- tags = ["automanaged"],
- deps = ["google/api/annotations.proto"],
+ tags = ["manual"],
+ deps = ["@go_googleapis//google/api:annotations_go_proto"],
)
go_library(
name = "go_default_library",
srcs = ["helloworld.pb.bm.go"],
- embed = ["v1_go_proto"],
+ embed = [":v1_go_proto"],
importpath = "go-common/app/tool/protoc-gen-bm/examples/helloworld/api/v1",
tags = ["automanaged"],
visibility = ["//visibility:public"],
```
恩、不解释了,应该都能看懂
#### 需要自定义 form tag
因为 blademaster 在 Bind parameters 时默认是大小写敏感的,而且没有自动转换驼峰与下划线,所以在定义 Proto message 时需要用 gogo 自定义一些 tag
```protobuf
message User {
// mid
int64 mid = 1 [(gogoproto.moretags) = "form:\"mid\" validate:\"required,min=1\""];
}
```
参考 https://github.com/gogo/protobuf/blob/master/extensions.md
### TODO
- [ ] 完善错误提示
- [ ] 更加完善的 google.api.http 支持
### Roadmap
- [x] 修改已有的工具实现读取 google.api.http option 生成 bm server
- [ ] 添加 bilibili.api.extra option扩展 google.api.http
### 已知问题
* 复杂结构问题,由于 http from 表达能力有限,无法很好的描述有些复杂的 protobuf message解决: 内嵌 protobuf 或者 使用 json
* 老项目兼容问题,有些项目会返回类似 map[string]interface{} 之类的结构,无法再 protobuf解决: 内嵌 json ?
### 参考文档
* [google.api.http 定义](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto)
* [grpc-gateway](https://github.com/grpc-ecosystem/grpc-gateway)
### client 代码生成
#### iOS 代码生成
TODO
#### Android 代码生成
TODO
/cc @liugang @zhoujiahui

View File

@@ -0,0 +1,32 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["generator.go"],
importpath = "go-common/app/tool/protoc-gen-bm/codegenerator",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"@com_github_golang_protobuf//proto:go_default_library",
"@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,39 @@
package codegenerator
import (
"fmt"
"io"
"io/ioutil"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
// ParseRequest parses a code generator request from a proto Message.
func ParseRequest(r io.Reader) (*plugin.CodeGeneratorRequest, error) {
input, err := ioutil.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("failed to read code generator request: %v", err)
}
req := new(plugin.CodeGeneratorRequest)
if err = proto.Unmarshal(input, req); err != nil {
return nil, fmt.Errorf("failed to unmarshal code generator request: %v", err)
}
return req, nil
}
// WriteResponse write a code generator response
func WriteResponse(w io.Writer, files []*plugin.CodeGeneratorResponse_File, inErr error) error {
var perrMsg *string
if inErr != nil {
errMsg := inErr.Error()
perrMsg = &errMsg
}
resp := &plugin.CodeGeneratorResponse{Error: perrMsg, File: files}
buf, err := proto.Marshal(resp)
if err != nil {
return err
}
_, err = w.Write(buf)
return err
}

View File

@@ -0,0 +1,44 @@
// Package v1 Code generated by go-common/app/tool/protoc-gen-bm. DO NOT EDIT.
package v1
import (
"context"
bm "go-common/library/net/http/blademaster"
)
// BMHelloServer interface as same as gGRPC server define
type BMHelloServer interface {
SayHello(context.Context, *HelloRequest) (*HelloReply, error)
Echo(context.Context, *EchoRequest) (*EchoReply, error)
}
// _BMServerHelloserver
type _BMServerHello struct {
BMHelloServer
}
func (b *_BMServerHello) bmHelloSayHelloHandler(c *bm.Context) {
req := new(HelloRequest)
if err := c.Bind(req); err != nil {
return
}
reply, err := b.SayHello(c.Context, req)
c.JSON(reply, err)
}
func (b *_BMServerHello) bmHelloEchoHandler(c *bm.Context) {
req := new(EchoRequest)
if err := c.Bind(req); err != nil {
return
}
reply, err := b.Echo(c.Context, req)
c.JSON(reply, err)
}
// RegisterHelloBMServer register bm server
func RegisterHelloBMServer(e *bm.Engine, s BMHelloServer) {
bs := &_BMServerHello{s}
e.GET("/hello", bs.bmHelloSayHelloHandler)
e.POST("/echo", bs.bmHelloEchoHandler)
}

View File

@@ -0,0 +1,318 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/helloworld/api/helloworld.proto
package v1
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// The request message containing the user's name.
type HelloRequest struct {
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HelloRequest) Reset() { *m = HelloRequest{} }
func (m *HelloRequest) String() string { return proto.CompactTextString(m) }
func (*HelloRequest) ProtoMessage() {}
func (*HelloRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_helloworld_240ffe8e5d7496cc, []int{0}
}
func (m *HelloRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelloRequest.Unmarshal(m, b)
}
func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic)
}
func (dst *HelloRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelloRequest.Merge(dst, src)
}
func (m *HelloRequest) XXX_Size() int {
return xxx_messageInfo_HelloRequest.Size(m)
}
func (m *HelloRequest) XXX_DiscardUnknown() {
xxx_messageInfo_HelloRequest.DiscardUnknown(m)
}
var xxx_messageInfo_HelloRequest proto.InternalMessageInfo
func (m *HelloRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
// The response message containing the greetings
type HelloReply struct {
Message string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HelloReply) Reset() { *m = HelloReply{} }
func (m *HelloReply) String() string { return proto.CompactTextString(m) }
func (*HelloReply) ProtoMessage() {}
func (*HelloReply) Descriptor() ([]byte, []int) {
return fileDescriptor_helloworld_240ffe8e5d7496cc, []int{1}
}
func (m *HelloReply) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelloReply.Unmarshal(m, b)
}
func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic)
}
func (dst *HelloReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelloReply.Merge(dst, src)
}
func (m *HelloReply) XXX_Size() int {
return xxx_messageInfo_HelloReply.Size(m)
}
func (m *HelloReply) XXX_DiscardUnknown() {
xxx_messageInfo_HelloReply.DiscardUnknown(m)
}
var xxx_messageInfo_HelloReply proto.InternalMessageInfo
func (m *HelloReply) GetMessage() string {
if m != nil {
return m.Message
}
return ""
}
type EchoRequest struct {
Content string `protobuf:"bytes,1,opt,name=content" json:"content,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *EchoRequest) Reset() { *m = EchoRequest{} }
func (m *EchoRequest) String() string { return proto.CompactTextString(m) }
func (*EchoRequest) ProtoMessage() {}
func (*EchoRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_helloworld_240ffe8e5d7496cc, []int{2}
}
func (m *EchoRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_EchoRequest.Unmarshal(m, b)
}
func (m *EchoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_EchoRequest.Marshal(b, m, deterministic)
}
func (dst *EchoRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_EchoRequest.Merge(dst, src)
}
func (m *EchoRequest) XXX_Size() int {
return xxx_messageInfo_EchoRequest.Size(m)
}
func (m *EchoRequest) XXX_DiscardUnknown() {
xxx_messageInfo_EchoRequest.DiscardUnknown(m)
}
var xxx_messageInfo_EchoRequest proto.InternalMessageInfo
func (m *EchoRequest) GetContent() string {
if m != nil {
return m.Content
}
return ""
}
type EchoReply struct {
Content string `protobuf:"bytes,1,opt,name=content" json:"content,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *EchoReply) Reset() { *m = EchoReply{} }
func (m *EchoReply) String() string { return proto.CompactTextString(m) }
func (*EchoReply) ProtoMessage() {}
func (*EchoReply) Descriptor() ([]byte, []int) {
return fileDescriptor_helloworld_240ffe8e5d7496cc, []int{3}
}
func (m *EchoReply) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_EchoReply.Unmarshal(m, b)
}
func (m *EchoReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_EchoReply.Marshal(b, m, deterministic)
}
func (dst *EchoReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_EchoReply.Merge(dst, src)
}
func (m *EchoReply) XXX_Size() int {
return xxx_messageInfo_EchoReply.Size(m)
}
func (m *EchoReply) XXX_DiscardUnknown() {
xxx_messageInfo_EchoReply.DiscardUnknown(m)
}
var xxx_messageInfo_EchoReply proto.InternalMessageInfo
func (m *EchoReply) GetContent() string {
if m != nil {
return m.Content
}
return ""
}
func init() {
proto.RegisterType((*HelloRequest)(nil), "helloworld.v1.HelloRequest")
proto.RegisterType((*HelloReply)(nil), "helloworld.v1.HelloReply")
proto.RegisterType((*EchoRequest)(nil), "helloworld.v1.EchoRequest")
proto.RegisterType((*EchoReply)(nil), "helloworld.v1.EchoReply")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for Hello service
type HelloClient interface {
// Sends a greeting
SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
Echo(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoReply, error)
}
type helloClient struct {
cc *grpc.ClientConn
}
func NewHelloClient(cc *grpc.ClientConn) HelloClient {
return &helloClient{cc}
}
func (c *helloClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) {
out := new(HelloReply)
err := grpc.Invoke(ctx, "/helloworld.v1.Hello/SayHello", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *helloClient) Echo(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoReply, error) {
out := new(EchoReply)
err := grpc.Invoke(ctx, "/helloworld.v1.Hello/Echo", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Hello service
type HelloServer interface {
// Sends a greeting
SayHello(context.Context, *HelloRequest) (*HelloReply, error)
Echo(context.Context, *EchoRequest) (*EchoReply, error)
}
func RegisterHelloServer(s *grpc.Server, srv HelloServer) {
s.RegisterService(&_Hello_serviceDesc, srv)
}
func _Hello_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HelloRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(HelloServer).SayHello(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/helloworld.v1.Hello/SayHello",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(HelloServer).SayHello(ctx, req.(*HelloRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Hello_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EchoRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(HelloServer).Echo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/helloworld.v1.Hello/Echo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(HelloServer).Echo(ctx, req.(*EchoRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Hello_serviceDesc = grpc.ServiceDesc{
ServiceName: "helloworld.v1.Hello",
HandlerType: (*HelloServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "SayHello",
Handler: _Hello_SayHello_Handler,
},
{
MethodName: "Echo",
Handler: _Hello_Echo_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/helloworld/api/helloworld.proto",
}
func init() {
proto.RegisterFile("examples/helloworld/api/helloworld.proto", fileDescriptor_helloworld_240ffe8e5d7496cc)
}
var fileDescriptor_helloworld_240ffe8e5d7496cc = []byte{
// 258 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x48, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0xcf, 0x48, 0xcd, 0xc9, 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1,
0x4f, 0x2c, 0xc8, 0x44, 0xe2, 0xea, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0xf1, 0x22, 0x89, 0x94,
0x19, 0x4a, 0xc9, 0xa4, 0xe7, 0xe7, 0xa7, 0xe7, 0xa4, 0x82, 0xd5, 0x26, 0xe6, 0xe5, 0xe5, 0x97,
0x24, 0x96, 0x64, 0xe6, 0xe7, 0x15, 0x43, 0x14, 0x2b, 0x29, 0x71, 0xf1, 0x78, 0x80, 0x94, 0x07,
0xa5, 0x16, 0x96, 0xa6, 0x16, 0x97, 0x08, 0x09, 0x71, 0xb1, 0xe4, 0x25, 0xe6, 0xa6, 0x4a, 0x30,
0x2a, 0x30, 0x6a, 0x70, 0x06, 0x81, 0xd9, 0x4a, 0x6a, 0x5c, 0x5c, 0x50, 0x35, 0x05, 0x39, 0x95,
0x42, 0x12, 0x5c, 0xec, 0xb9, 0xa9, 0xc5, 0xc5, 0x89, 0xe9, 0x30, 0x45, 0x30, 0xae, 0x92, 0x3a,
0x17, 0xb7, 0x6b, 0x72, 0x06, 0xdc, 0x28, 0x09, 0x2e, 0xf6, 0xe4, 0xfc, 0xbc, 0x92, 0xd4, 0xbc,
0x12, 0x98, 0x42, 0x28, 0x57, 0x49, 0x95, 0x8b, 0x13, 0xa2, 0x10, 0x6a, 0x1e, 0x76, 0x65, 0x46,
0x2b, 0x18, 0xb9, 0x58, 0xc1, 0x16, 0x0b, 0x05, 0x71, 0x71, 0x04, 0x27, 0x56, 0x42, 0xd8, 0xd2,
0x7a, 0x28, 0xfe, 0xd3, 0x43, 0x76, 0xbe, 0x94, 0x24, 0x76, 0xc9, 0x82, 0x9c, 0x4a, 0x25, 0xbe,
0xa6, 0xcb, 0x4f, 0x26, 0x33, 0x71, 0x08, 0xb1, 0x41, 0x42, 0x4c, 0xc8, 0x9b, 0x8b, 0x05, 0xe4,
0x08, 0x21, 0x29, 0x34, 0x2d, 0x48, 0x5e, 0x90, 0x92, 0xc0, 0x2a, 0x07, 0x32, 0x8d, 0x17, 0x6c,
0x1a, 0xbb, 0x12, 0xab, 0x7e, 0x6a, 0x72, 0x46, 0xbe, 0x13, 0x4b, 0x14, 0x53, 0x99, 0x61, 0x12,
0x1b, 0x38, 0x4c, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x4a, 0x51, 0xfb, 0x90, 0xac, 0x01,
0x00, 0x00,
}

View File

@@ -0,0 +1,39 @@
syntax = "proto3";
package helloworld.v1;
import "google/api/annotations.proto";
option go_package = "v1";
// The greeting service definition.
service Hello {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
get:"/hello"
};
}
rpc Echo(EchoRequest) returns (EchoReply) {
option (google.api.http) = {
post:"/echo"
};
}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
message EchoRequest {
string content = 1;
}
message EchoReply {
string content = 1;
}

View File

@@ -0,0 +1,22 @@
package main
import (
"log"
"go-common/app/tool/protoc-gen-bm/examples/helloworld/api"
"go-common/app/tool/protoc-gen-bm/examples/helloworld/service"
bm "go-common/library/net/http/blademaster"
)
func main() {
engine := bm.NewServer(nil)
// 注册 middleware 支持正则匹配
engine.Inject("^/echo", func(c *bm.Context) {
// do something
})
s := new(service.Service)
v1.RegisterHelloBMServer(engine, s)
if err := engine.Run("127.0.0.1:8000"); err != nil {
log.Fatal(err)
}
}

View File

@@ -0,0 +1,26 @@
package service
import (
"context"
"fmt"
"go-common/app/tool/protoc-gen-bm/examples/helloworld/api"
)
// Service .
type Service struct{}
var _ v1.HelloServer = &Service{}
var _ v1.BMHelloServer = &Service{}
// SayHello .
func (s *Service) SayHello(ctx context.Context, req *v1.HelloRequest) (*v1.HelloReply, error) {
return &v1.HelloReply{
Message: fmt.Sprintf("hello %s", req.Name),
}, nil
}
// Echo .
func (s *Service) Echo(ctx context.Context, req *v1.EchoRequest) (*v1.EchoReply, error) {
return &v1.EchoReply{Content: req.Content}, nil
}

View File

@@ -0,0 +1,41 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"bm_generate.go",
"genbm.go",
"http_descriptor.go",
],
importpath = "go-common/app/tool/protoc-gen-bm/genbm",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/tool/protoc-gen-bm/generator:go_default_library",
"//app/tool/protoc-gen-bm/util:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/google.golang.org/genproto/googleapis/api/annotations:go_default_library",
"@com_github_golang_protobuf//proto:go_default_library",
"@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library",
"@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,143 @@
package genbm
import (
"fmt"
"io"
"go-common/app/tool/protoc-gen-bm/util"
)
const (
bmPkgPath = "go-common/library/net/http/blademaster"
)
// BMGenerate generate bm server code
type BMGenerate struct {
target io.Writer
packageName string
descs []*BMServerDescriptor
err error
jsonpb bool
}
// NewBMGenerate BMGenerate
func NewBMGenerate(packageName string, descs []*BMServerDescriptor, jsonpb bool) *BMGenerate {
return &BMGenerate{
packageName: packageName,
descs: descs,
jsonpb: jsonpb,
}
}
// Generate code
func (b *BMGenerate) Generate(target io.Writer) error {
b.target = target
methodsCount := 0
for _, desc := range b.descs {
methodsCount += len(desc.Methods)
}
// if not methods found, can't generate anything
if methodsCount == 0 {
return nil
}
b.generatePackageImport()
for _, desc := range b.descs {
b.generateServer(desc)
}
return b.err
}
// P print code
func (b *BMGenerate) P(args ...interface{}) {
if b.err != nil {
return
}
args = append(args, "\n")
_, b.err = fmt.Fprint(b.target, args...)
}
func (b *BMGenerate) generatePackageImport() {
b.P("// Package ", b.packageName, " Code generated by go-common/app/tool/protoc-gen-bm. DO NOT EDIT.")
b.P("package ", b.packageName)
b.P()
b.P("import (")
b.P(" \"context\"")
if b.jsonpb {
b.P(" \"bytes\"")
b.P(" \"encoding/json\"")
b.P()
b.P(" \"go-common/app/tool/protoc-gen-bm/jsonpb\"")
}
b.P()
b.P(" bm \"", bmPkgPath, "\"")
b.P(")")
b.P()
}
func (b *BMGenerate) generateServer(desc *BMServerDescriptor) {
b.generateServerInterface(desc)
b.generateServerHandler(desc)
b.generateRegisterFunc(desc)
}
func (b *BMGenerate) generateServerInterface(desc *BMServerDescriptor) {
serviceName := util.CamelCase(desc.Name)
b.P(fmt.Sprintf("// BM%sServer interface as same as gGRPC server define", serviceName))
b.P("type BM", serviceName, "Server interface {")
for _, method := range desc.Methods {
b.P(" ", util.CamelCase(method.Name), fmt.Sprintf("(context.Context, *%s) (*%s, error)", method.RequestType, method.ReplyType))
}
b.P("}")
b.P()
}
func (b *BMGenerate) generateServerHandler(desc *BMServerDescriptor) {
serviceName := util.CamelCase(desc.Name)
receiverName := fmt.Sprintf("_BMServer%s", serviceName)
b.P("// _BMServer", serviceName, "server")
b.P("type ", receiverName, " struct {")
b.P(" BM", serviceName, "Server")
b.P("}")
b.P()
for _, method := range desc.Methods {
methodName := util.CamelCase(method.Name)
funcName := fmt.Sprintf("bm%s%sHandler", serviceName, methodName)
b.P(fmt.Sprintf("func (b *%s) ", receiverName), funcName, "(c *bm.Context) {")
// bind req
b.P(fmt.Sprintf(" req := new(%s)", method.RequestType))
b.P(fmt.Sprintf(" if err := c.Bind(req); err != nil {"))
b.P(" return")
b.P(" }")
// call service
b.P(fmt.Sprintf(" reply, err := b.%s(c.Context, req)", methodName))
if b.jsonpb {
b.P(" if err != nil {")
b.P(" c.JSON(nil, err)")
b.P(" return")
b.P(" }")
b.P(" body := &bytes.Buffer{}")
b.P(" marshaler := jsonpb.Marshaler{EmitDefaults: true, OrigName: true}")
b.P(" err = marshaler.Marshal(body, reply)")
b.P(" c.JSON(json.RawMessage(body.Bytes()), err)")
} else {
b.P(" c.JSON(reply, err)")
}
b.P("}")
b.P()
}
}
func (b *BMGenerate) generateRegisterFunc(desc *BMServerDescriptor) {
serviceName := util.CamelCase(desc.Name)
receiverName := fmt.Sprintf("_BMServer%s", serviceName)
b.P(fmt.Sprintf("// Register%sBMServer register bm server", serviceName))
b.P(fmt.Sprintf("func Register%sBMServer(e *bm.Engine, s BM%sServer) {", serviceName, serviceName))
b.P(fmt.Sprintf(" bs := &%s{s}", receiverName))
for _, method := range desc.Methods {
methodName := util.CamelCase(method.Name)
funcName := fmt.Sprintf("bm%s%sHandler", serviceName, methodName)
b.P(fmt.Sprintf(" e.%s(\"%s\", bs.%s)", method.Method, method.PathPattern, funcName))
}
b.P("}")
b.P()
}

View File

@@ -0,0 +1,131 @@
package genbm
import (
"bytes"
"go/format"
"os"
"path/filepath"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"go-common/app/tool/protoc-gen-bm/generator"
)
// New blademaster server code generator
func New(jsonpb bool) generator.Generator {
return &genbm{jsonpb: jsonpb}
}
type genbm struct {
jsonpb bool
}
func (g *genbm) Generate(req *plugin.CodeGeneratorRequest) ([]*plugin.CodeGeneratorResponse_File, error) {
var resp []*plugin.CodeGeneratorResponse_File
files := req.GetProtoFile()
for _, file := range files {
respFile, ok, err := g.generateFile(file)
if err != nil {
return resp, err
}
if ok {
resp = append(resp, respFile)
}
}
return resp, nil
}
func (g *genbm) generateFile(file *descriptor.FileDescriptorProto) (*plugin.CodeGeneratorResponse_File, bool, error) {
glog.V(1).Infof("process proto file %s", file.GetName())
services := file.GetService()
if len(services) == 0 {
glog.V(5).Infof("proto file %s not included service descriptor", file.GetName())
return nil, false, nil
}
var descs []*BMServerDescriptor
for _, service := range services {
server, err := ParseBMServer(service)
if err != nil {
return nil, false, err
}
descs = append(descs, server)
}
buf := new(bytes.Buffer)
goPackageName := GetGoPackageName(file)
gen := NewBMGenerate(goPackageName, descs, g.jsonpb)
if err := gen.Generate(buf); err != nil {
return nil, false, err
}
// format code
data, err := format.Source(buf.Bytes())
if err != nil {
return nil, false, err
}
content := string(data)
// no content
if len(content) == 0 {
return nil, false, nil
}
target := TargetFilePath(file)
glog.V(1).Infof("generate code to %s", target)
return &plugin.CodeGeneratorResponse_File{
Content: &content,
Name: &target,
}, true, nil
}
// TargetFilePath find target file path
func TargetFilePath(file *descriptor.FileDescriptorProto) string {
fpath := file.GetName()
protoDir := filepath.Dir(fpath)
noExt := filepath.Base(fpath)
for i := len(noExt) - 1; i >= 0 && !os.IsPathSeparator(noExt[i]); i-- {
if noExt[i] == '.' {
noExt = noExt[:i]
}
}
target := noExt + ".pb.bm.go"
options := file.GetOptions()
if options != nil {
goPackage := options.GetGoPackage()
if goPackage != "" {
goPackage = strings.Split(goPackage, ";")[0]
if strings.Contains(goPackage, "/") {
return filepath.Join(goPackage, target)
}
}
}
return filepath.Join(protoDir, target)
}
// GetGoPackageName last element from proto package name or go_package option
func GetGoPackageName(file *descriptor.FileDescriptorProto) string {
var goPackageName string
protoPackage := file.GetPackage()
goPackageName = splitLastElem(protoPackage, ".")
options := file.GetOptions()
if options == nil {
return goPackageName
}
if goPackage := options.GetGoPackage(); goPackage != "" {
if strings.Contains(goPackage, ";") {
goPackageName = splitLastElem(goPackage, ";")
} else {
goPackageName = splitLastElem(goPackage, "/")
}
}
return goPackageName
}
func splitLastElem(s string, seq string) string {
seqs := strings.Split(s, seq)
return seqs[len(seqs)-1]
}

View File

@@ -0,0 +1,107 @@
package genbm
import (
"fmt"
"net/http"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"google.golang.org/genproto/googleapis/api/annotations"
)
// BMServerDescriptor descriptor for BM server
type BMServerDescriptor struct {
Name string
ProtoService *descriptor.ServiceDescriptorProto
Methods []*BMMethodDescriptor
}
// BMMethodDescriptor descriptor for BM http method
type BMMethodDescriptor struct {
Name string
Method string
PathPattern string
RequestType string
ReplyType string
ProtoMethod *descriptor.MethodDescriptorProto
HTTPRule *annotations.HttpRule
}
// ParseBMServer parse BMServerDescriptor form service descriptor proto
func ParseBMServer(service *descriptor.ServiceDescriptorProto) (*BMServerDescriptor, error) {
glog.V(1).Infof("parse bmserver from service %s", service.GetName())
serverDesc := &BMServerDescriptor{
Name: service.GetName(),
ProtoService: service,
}
for _, method := range service.GetMethod() {
if !HasHTTPRuleOptions(method) {
glog.V(5).Infof("method %s not include http rule, skipped", method.GetName())
continue
}
bmMethod, err := ParseBMMethod(method)
if err != nil {
return nil, err
}
serverDesc.Methods = append(serverDesc.Methods, bmMethod)
}
return serverDesc, nil
}
// ParseBMMethod parse BMMethodDescriptor form method descriptor proto
func ParseBMMethod(method *descriptor.MethodDescriptorProto) (*BMMethodDescriptor, error) {
glog.V(1).Infof("parse bmmethod from method %s", method.GetName())
ext, err := proto.GetExtension(method.GetOptions(), annotations.E_Http)
if err != nil {
return nil, fmt.Errorf("get extension error: %s", err)
}
rule := ext.(*annotations.HttpRule)
var httpMethod string
var pathPattern string
switch pattern := rule.Pattern.(type) {
case *annotations.HttpRule_Get:
pathPattern = pattern.Get
httpMethod = http.MethodGet
case *annotations.HttpRule_Put:
pathPattern = pattern.Put
httpMethod = http.MethodPut
case *annotations.HttpRule_Post:
pathPattern = pattern.Post
httpMethod = http.MethodPost
case *annotations.HttpRule_Patch:
pathPattern = pattern.Patch
httpMethod = http.MethodPatch
case *annotations.HttpRule_Delete:
pathPattern = pattern.Delete
httpMethod = http.MethodDelete
default:
return nil, fmt.Errorf("unsupport http pattern %s", rule.Pattern)
}
if len(rule.AdditionalBindings) != 0 {
glog.Warningf("unsupport additional binding, additional binding will be ignored")
}
// TODO: support use type from other package
requestType := splitLastElem(method.GetInputType(), ".")
replyType := splitLastElem(method.GetOutputType(), ".")
bmMethod := &BMMethodDescriptor{
Name: method.GetName(),
Method: httpMethod,
PathPattern: pathPattern,
RequestType: requestType,
ReplyType: replyType,
ProtoMethod: method,
HTTPRule: rule,
}
glog.V(5).Infof("bmMethod %s: %s %s, Request:%s Reply: %s", bmMethod.Name, bmMethod.Method, bmMethod.PathPattern, bmMethod.RequestType, bmMethod.ReplyType)
return bmMethod, nil
}
// HasHTTPRuleOptions check method has httprule extension
func HasHTTPRuleOptions(method *descriptor.MethodDescriptorProto) bool {
options := method.GetOptions()
if options == nil {
return false
}
return proto.HasExtension(options, annotations.E_Http)
}

View File

@@ -0,0 +1,29 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["generator.go"],
importpath = "go-common/app/tool/protoc-gen-bm/generator",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = ["@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,12 @@
// Package generator provides an abstract interface to code generators.
package generator
import (
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
// Generator is an abstraction of code generators.
type Generator interface {
// Generate generates output files from input .proto files.
Generate(req *plugin.CodeGeneratorRequest) ([]*plugin.CodeGeneratorResponse_File, error)
}

View File

@@ -0,0 +1,35 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["jsonpb.go"],
importpath = "go-common/app/tool/protoc-gen-bm/jsonpb",
tags = ["manual"],
visibility = ["//visibility:public"],
deps = [
"@com_github_golang_protobuf//proto:go_default_library",
"@com_github_golang_protobuf//ptypes/struct:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/tool/protoc-gen-bm/jsonpb/jsonpb_test_proto:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,73 @@
load(
"@io_bazel_rules_go//proto:def.bzl",
"go_proto_library",
)
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
proto_library(
name = "jsonpb_proto",
srcs = [
"more_test_objects.proto",
"test_objects.proto",
],
tags = ["manual"],
deps = [
"@com_google_protobuf//:any_proto",
"@com_google_protobuf//:duration_proto",
"@com_google_protobuf//:struct_proto",
"@com_google_protobuf//:timestamp_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
go_proto_library(
name = "jsonpb_go_proto",
compilers = ["@io_bazel_rules_go//proto:go_proto"],
importpath = "go-common/app/tool/protoc-gen-bm/jsonpb/jsonpb_test_proto",
proto = ":jsonpb_proto",
tags = ["manual"],
deps = [
"@com_github_golang_protobuf//ptypes/struct:go_default_library",
"@com_github_golang_protobuf//ptypes/wrappers:go_default_library",
"@io_bazel_rules_go//proto/wkt:any_go_proto",
"@io_bazel_rules_go//proto/wkt:duration_go_proto",
"@io_bazel_rules_go//proto/wkt:timestamp_go_proto",
],
)
go_library(
name = "go_default_library",
srcs = [],
embed = [":jsonpb_go_proto"],
importpath = "go-common/app/tool/protoc-gen-bm/jsonpb/jsonpb_test_proto",
tags = ["manual"],
visibility = ["//visibility:public"],
deps = [
"@com_github_golang_protobuf//proto:go_default_library",
"@com_github_golang_protobuf//ptypes/struct:go_default_library",
"@com_github_golang_protobuf//ptypes/wrappers:go_default_library",
"@io_bazel_rules_go//proto/wkt:any_go_proto",
"@io_bazel_rules_go//proto/wkt:duration_go_proto",
"@io_bazel_rules_go//proto/wkt:timestamp_go_proto",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,368 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: more_test_objects.proto
package jsonpb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type Numeral int32
const (
Numeral_UNKNOWN Numeral = 0
Numeral_ARABIC Numeral = 1
Numeral_ROMAN Numeral = 2
)
var Numeral_name = map[int32]string{
0: "UNKNOWN",
1: "ARABIC",
2: "ROMAN",
}
var Numeral_value = map[string]int32{
"UNKNOWN": 0,
"ARABIC": 1,
"ROMAN": 2,
}
func (x Numeral) String() string {
return proto.EnumName(Numeral_name, int32(x))
}
func (Numeral) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{0}
}
type Simple3 struct {
Dub float64 `protobuf:"fixed64,1,opt,name=dub,proto3" json:"dub,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Simple3) Reset() { *m = Simple3{} }
func (m *Simple3) String() string { return proto.CompactTextString(m) }
func (*Simple3) ProtoMessage() {}
func (*Simple3) Descriptor() ([]byte, []int) {
return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{0}
}
func (m *Simple3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Simple3.Unmarshal(m, b)
}
func (m *Simple3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Simple3.Marshal(b, m, deterministic)
}
func (dst *Simple3) XXX_Merge(src proto.Message) {
xxx_messageInfo_Simple3.Merge(dst, src)
}
func (m *Simple3) XXX_Size() int {
return xxx_messageInfo_Simple3.Size(m)
}
func (m *Simple3) XXX_DiscardUnknown() {
xxx_messageInfo_Simple3.DiscardUnknown(m)
}
var xxx_messageInfo_Simple3 proto.InternalMessageInfo
func (m *Simple3) GetDub() float64 {
if m != nil {
return m.Dub
}
return 0
}
type SimpleSlice3 struct {
Slices []string `protobuf:"bytes,1,rep,name=slices,proto3" json:"slices,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SimpleSlice3) Reset() { *m = SimpleSlice3{} }
func (m *SimpleSlice3) String() string { return proto.CompactTextString(m) }
func (*SimpleSlice3) ProtoMessage() {}
func (*SimpleSlice3) Descriptor() ([]byte, []int) {
return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{1}
}
func (m *SimpleSlice3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SimpleSlice3.Unmarshal(m, b)
}
func (m *SimpleSlice3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SimpleSlice3.Marshal(b, m, deterministic)
}
func (dst *SimpleSlice3) XXX_Merge(src proto.Message) {
xxx_messageInfo_SimpleSlice3.Merge(dst, src)
}
func (m *SimpleSlice3) XXX_Size() int {
return xxx_messageInfo_SimpleSlice3.Size(m)
}
func (m *SimpleSlice3) XXX_DiscardUnknown() {
xxx_messageInfo_SimpleSlice3.DiscardUnknown(m)
}
var xxx_messageInfo_SimpleSlice3 proto.InternalMessageInfo
func (m *SimpleSlice3) GetSlices() []string {
if m != nil {
return m.Slices
}
return nil
}
type SimpleMap3 struct {
Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy,proto3" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SimpleMap3) Reset() { *m = SimpleMap3{} }
func (m *SimpleMap3) String() string { return proto.CompactTextString(m) }
func (*SimpleMap3) ProtoMessage() {}
func (*SimpleMap3) Descriptor() ([]byte, []int) {
return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{2}
}
func (m *SimpleMap3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SimpleMap3.Unmarshal(m, b)
}
func (m *SimpleMap3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SimpleMap3.Marshal(b, m, deterministic)
}
func (dst *SimpleMap3) XXX_Merge(src proto.Message) {
xxx_messageInfo_SimpleMap3.Merge(dst, src)
}
func (m *SimpleMap3) XXX_Size() int {
return xxx_messageInfo_SimpleMap3.Size(m)
}
func (m *SimpleMap3) XXX_DiscardUnknown() {
xxx_messageInfo_SimpleMap3.DiscardUnknown(m)
}
var xxx_messageInfo_SimpleMap3 proto.InternalMessageInfo
func (m *SimpleMap3) GetStringy() map[string]string {
if m != nil {
return m.Stringy
}
return nil
}
type SimpleNull3 struct {
Simple *Simple3 `protobuf:"bytes,1,opt,name=simple,proto3" json:"simple,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SimpleNull3) Reset() { *m = SimpleNull3{} }
func (m *SimpleNull3) String() string { return proto.CompactTextString(m) }
func (*SimpleNull3) ProtoMessage() {}
func (*SimpleNull3) Descriptor() ([]byte, []int) {
return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{3}
}
func (m *SimpleNull3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SimpleNull3.Unmarshal(m, b)
}
func (m *SimpleNull3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SimpleNull3.Marshal(b, m, deterministic)
}
func (dst *SimpleNull3) XXX_Merge(src proto.Message) {
xxx_messageInfo_SimpleNull3.Merge(dst, src)
}
func (m *SimpleNull3) XXX_Size() int {
return xxx_messageInfo_SimpleNull3.Size(m)
}
func (m *SimpleNull3) XXX_DiscardUnknown() {
xxx_messageInfo_SimpleNull3.DiscardUnknown(m)
}
var xxx_messageInfo_SimpleNull3 proto.InternalMessageInfo
func (m *SimpleNull3) GetSimple() *Simple3 {
if m != nil {
return m.Simple
}
return nil
}
type Mappy struct {
Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy,proto3" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
Strry map[string]string `protobuf:"bytes,2,rep,name=strry,proto3" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
Objjy map[int32]*Simple3 `protobuf:"bytes,3,rep,name=objjy,proto3" json:"objjy,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
Buggy map[int64]string `protobuf:"bytes,4,rep,name=buggy,proto3" json:"buggy,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
Booly map[bool]bool `protobuf:"bytes,5,rep,name=booly,proto3" json:"booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
Enumy map[string]Numeral `protobuf:"bytes,6,rep,name=enumy,proto3" json:"enumy,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3,enum=jsonpb.Numeral"`
S32Booly map[int32]bool `protobuf:"bytes,7,rep,name=s32booly,proto3" json:"s32booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
S64Booly map[int64]bool `protobuf:"bytes,8,rep,name=s64booly,proto3" json:"s64booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
U32Booly map[uint32]bool `protobuf:"bytes,9,rep,name=u32booly,proto3" json:"u32booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
U64Booly map[uint64]bool `protobuf:"bytes,10,rep,name=u64booly,proto3" json:"u64booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Mappy) Reset() { *m = Mappy{} }
func (m *Mappy) String() string { return proto.CompactTextString(m) }
func (*Mappy) ProtoMessage() {}
func (*Mappy) Descriptor() ([]byte, []int) {
return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{4}
}
func (m *Mappy) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Mappy.Unmarshal(m, b)
}
func (m *Mappy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Mappy.Marshal(b, m, deterministic)
}
func (dst *Mappy) XXX_Merge(src proto.Message) {
xxx_messageInfo_Mappy.Merge(dst, src)
}
func (m *Mappy) XXX_Size() int {
return xxx_messageInfo_Mappy.Size(m)
}
func (m *Mappy) XXX_DiscardUnknown() {
xxx_messageInfo_Mappy.DiscardUnknown(m)
}
var xxx_messageInfo_Mappy proto.InternalMessageInfo
func (m *Mappy) GetNummy() map[int64]int32 {
if m != nil {
return m.Nummy
}
return nil
}
func (m *Mappy) GetStrry() map[string]string {
if m != nil {
return m.Strry
}
return nil
}
func (m *Mappy) GetObjjy() map[int32]*Simple3 {
if m != nil {
return m.Objjy
}
return nil
}
func (m *Mappy) GetBuggy() map[int64]string {
if m != nil {
return m.Buggy
}
return nil
}
func (m *Mappy) GetBooly() map[bool]bool {
if m != nil {
return m.Booly
}
return nil
}
func (m *Mappy) GetEnumy() map[string]Numeral {
if m != nil {
return m.Enumy
}
return nil
}
func (m *Mappy) GetS32Booly() map[int32]bool {
if m != nil {
return m.S32Booly
}
return nil
}
func (m *Mappy) GetS64Booly() map[int64]bool {
if m != nil {
return m.S64Booly
}
return nil
}
func (m *Mappy) GetU32Booly() map[uint32]bool {
if m != nil {
return m.U32Booly
}
return nil
}
func (m *Mappy) GetU64Booly() map[uint64]bool {
if m != nil {
return m.U64Booly
}
return nil
}
func init() {
proto.RegisterType((*Simple3)(nil), "jsonpb.Simple3")
proto.RegisterType((*SimpleSlice3)(nil), "jsonpb.SimpleSlice3")
proto.RegisterType((*SimpleMap3)(nil), "jsonpb.SimpleMap3")
proto.RegisterMapType((map[string]string)(nil), "jsonpb.SimpleMap3.StringyEntry")
proto.RegisterType((*SimpleNull3)(nil), "jsonpb.SimpleNull3")
proto.RegisterType((*Mappy)(nil), "jsonpb.Mappy")
proto.RegisterMapType((map[bool]bool)(nil), "jsonpb.Mappy.BoolyEntry")
proto.RegisterMapType((map[int64]string)(nil), "jsonpb.Mappy.BuggyEntry")
proto.RegisterMapType((map[string]Numeral)(nil), "jsonpb.Mappy.EnumyEntry")
proto.RegisterMapType((map[int64]int32)(nil), "jsonpb.Mappy.NummyEntry")
proto.RegisterMapType((map[int32]*Simple3)(nil), "jsonpb.Mappy.ObjjyEntry")
proto.RegisterMapType((map[int32]bool)(nil), "jsonpb.Mappy.S32boolyEntry")
proto.RegisterMapType((map[int64]bool)(nil), "jsonpb.Mappy.S64boolyEntry")
proto.RegisterMapType((map[string]string)(nil), "jsonpb.Mappy.StrryEntry")
proto.RegisterMapType((map[uint32]bool)(nil), "jsonpb.Mappy.U32boolyEntry")
proto.RegisterMapType((map[uint64]bool)(nil), "jsonpb.Mappy.U64boolyEntry")
proto.RegisterEnum("jsonpb.Numeral", Numeral_name, Numeral_value)
}
func init() {
proto.RegisterFile("more_test_objects.proto", fileDescriptor_more_test_objects_bef0d79b901f4c4a)
}
var fileDescriptor_more_test_objects_bef0d79b901f4c4a = []byte{
// 526 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdd, 0x6b, 0xdb, 0x3c,
0x14, 0x87, 0x5f, 0x27, 0xf5, 0xd7, 0x49, 0xfb, 0x2e, 0x88, 0xb1, 0x99, 0xf4, 0x62, 0xc5, 0xb0,
0xad, 0x0c, 0xe6, 0x8b, 0x78, 0x74, 0x5d, 0x77, 0x95, 0x8e, 0x5e, 0x94, 0x11, 0x07, 0x1c, 0xc2,
0x2e, 0x4b, 0xdc, 0x99, 0x90, 0xcc, 0x5f, 0xd8, 0xd6, 0xc0, 0xd7, 0xfb, 0xbb, 0x07, 0xe3, 0x48,
0x72, 0x2d, 0x07, 0x85, 0x6c, 0x77, 0x52, 0x7e, 0xcf, 0xe3, 0x73, 0x24, 0x1d, 0x02, 0x2f, 0xd3,
0xbc, 0x8c, 0x1f, 0xea, 0xb8, 0xaa, 0x1f, 0xf2, 0x68, 0x17, 0x3f, 0xd6, 0x95, 0x57, 0x94, 0x79,
0x9d, 0x13, 0x63, 0x57, 0xe5, 0x59, 0x11, 0xb9, 0xe7, 0x60, 0x2e, 0xb7, 0x69, 0x91, 0xc4, 0x3e,
0x19, 0xc3, 0xf0, 0x3b, 0x8d, 0x1c, 0xed, 0x42, 0xbb, 0xd4, 0x42, 0x5c, 0xba, 0x6f, 0xe0, 0x94,
0x87, 0xcb, 0x64, 0xfb, 0x18, 0xfb, 0xe4, 0x05, 0x18, 0x15, 0xae, 0x2a, 0x47, 0xbb, 0x18, 0x5e,
0xda, 0xa1, 0xd8, 0xb9, 0xbf, 0x34, 0x00, 0x0e, 0xce, 0xd7, 0x85, 0x4f, 0x3e, 0x81, 0x59, 0xd5,
0xe5, 0x36, 0xdb, 0x34, 0x8c, 0x1b, 0x4d, 0x5f, 0x79, 0xbc, 0x9a, 0xd7, 0x41, 0xde, 0x92, 0x13,
0x77, 0x59, 0x5d, 0x36, 0x61, 0xcb, 0x4f, 0x6e, 0xe0, 0x54, 0x0e, 0xb0, 0xa7, 0x1f, 0x71, 0xc3,
0x7a, 0xb2, 0x43, 0x5c, 0x92, 0xe7, 0xa0, 0xff, 0x5c, 0x27, 0x34, 0x76, 0x06, 0xec, 0x37, 0xbe,
0xb9, 0x19, 0x5c, 0x6b, 0xee, 0x15, 0x8c, 0xf8, 0xf7, 0x03, 0x9a, 0x24, 0x3e, 0x79, 0x0b, 0x46,
0xc5, 0xb6, 0xcc, 0x1e, 0x4d, 0x9f, 0xf5, 0x9b, 0xf0, 0x43, 0x11, 0xbb, 0xbf, 0x2d, 0xd0, 0xe7,
0xeb, 0xa2, 0x68, 0x88, 0x07, 0x7a, 0x46, 0xd3, 0xb4, 0x6d, 0xdb, 0x69, 0x0d, 0x96, 0x7a, 0x01,
0x46, 0xbc, 0x5f, 0x8e, 0x21, 0x5f, 0xd5, 0x65, 0xd9, 0x38, 0x03, 0x15, 0xbf, 0xc4, 0x48, 0xf0,
0x0c, 0x43, 0x3e, 0x8f, 0x76, 0xbb, 0xc6, 0x19, 0xaa, 0xf8, 0x05, 0x46, 0x82, 0x67, 0x18, 0xf2,
0x11, 0xdd, 0x6c, 0x1a, 0xe7, 0x44, 0xc5, 0xdf, 0x62, 0x24, 0x78, 0x86, 0x31, 0x3e, 0xcf, 0x93,
0xc6, 0xd1, 0x95, 0x3c, 0x46, 0x2d, 0x8f, 0x6b, 0xe4, 0xe3, 0x8c, 0xa6, 0x8d, 0x63, 0xa8, 0xf8,
0x3b, 0x8c, 0x04, 0xcf, 0x30, 0xf2, 0x11, 0xac, 0xca, 0x9f, 0xf2, 0x12, 0x26, 0x53, 0xce, 0xf7,
0x8e, 0x2c, 0x52, 0x6e, 0x3d, 0xc1, 0x4c, 0xbc, 0xfa, 0xc0, 0x45, 0x4b, 0x29, 0x8a, 0xb4, 0x15,
0xc5, 0x16, 0x45, 0xda, 0x56, 0xb4, 0x55, 0xe2, 0xaa, 0x5f, 0x91, 0x4a, 0x15, 0x69, 0x5b, 0x11,
0x94, 0x62, 0xbf, 0x62, 0x0b, 0x4f, 0xae, 0x01, 0xba, 0x87, 0x96, 0xe7, 0x6f, 0xa8, 0x98, 0x3f,
0x5d, 0x9a, 0x3f, 0x34, 0xbb, 0x27, 0xff, 0x97, 0xc9, 0x9d, 0xdc, 0x03, 0x74, 0x8f, 0x2f, 0x9b,
0x3a, 0x37, 0x5f, 0xcb, 0xa6, 0x62, 0x92, 0xfb, 0x4d, 0x74, 0x73, 0x71, 0xac, 0x7d, 0x7b, 0xdf,
0x7c, 0xba, 0x10, 0xd9, 0xb4, 0x14, 0xa6, 0xb5, 0xd7, 0x7e, 0x37, 0x2b, 0x8a, 0x83, 0xf7, 0xda,
0xff, 0xbf, 0x6b, 0x3f, 0xa0, 0x69, 0x5c, 0xae, 0x13, 0xf9, 0x53, 0x9f, 0xe1, 0xac, 0x37, 0x43,
0x8a, 0xcb, 0x38, 0xdc, 0x07, 0xca, 0xf2, 0xab, 0x1e, 0x3b, 0xfe, 0xbe, 0xbc, 0x3a, 0x54, 0xf9,
0xec, 0x6f, 0xe4, 0x43, 0x95, 0x4f, 0x8e, 0xc8, 0xef, 0xde, 0x83, 0x29, 0x6e, 0x82, 0x8c, 0xc0,
0x5c, 0x05, 0x5f, 0x83, 0xc5, 0xb7, 0x60, 0xfc, 0x1f, 0x01, 0x30, 0x66, 0xe1, 0xec, 0xf6, 0xfe,
0xcb, 0x58, 0x23, 0x36, 0xe8, 0xe1, 0x62, 0x3e, 0x0b, 0xc6, 0x83, 0xc8, 0x60, 0x7f, 0xe0, 0xfe,
0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x34, 0xaf, 0xdb, 0x05, 0x00, 0x00,
}

View File

@@ -0,0 +1,69 @@
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2015 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package jsonpb;
message Simple3 {
double dub = 1;
}
message SimpleSlice3 {
repeated string slices = 1;
}
message SimpleMap3 {
map<string,string> stringy = 1;
}
message SimpleNull3 {
Simple3 simple = 1;
}
enum Numeral {
UNKNOWN = 0;
ARABIC = 1;
ROMAN = 2;
}
message Mappy {
map<int64, int32> nummy = 1;
map<string, string> strry = 2;
map<int32, Simple3> objjy = 3;
map<int64, string> buggy = 4;
map<bool, bool> booly = 5;
map<string, Numeral> enumy = 6;
map<int32, bool> s32booly = 7;
map<int64, bool> s64booly = 8;
map<uint32, bool> u32booly = 9;
map<uint64, bool> u64booly = 10;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,179 @@
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2015 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
import "google/protobuf/any.proto";
import "google/protobuf/duration.proto";
import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/wrappers.proto";
package jsonpb;
// Test message for holding primitive types.
message Simple {
optional bool o_bool = 1;
optional int32 o_int32 = 2;
optional int32 o_int32_str = 3;
optional int64 o_int64 = 4;
optional int64 o_int64_str = 5;
optional uint32 o_uint32 = 6;
optional uint32 o_uint32_str = 7;
optional uint64 o_uint64 = 8;
optional uint64 o_uint64_str = 9;
optional sint32 o_sint32 = 10;
optional sint32 o_sint32_str = 11;
optional sint64 o_sint64 = 12;
optional sint64 o_sint64_str = 13;
optional float o_float = 14;
optional float o_float_str = 15;
optional double o_double = 16;
optional double o_double_str = 17;
optional string o_string = 18;
optional bytes o_bytes = 19;
}
// Test message for holding special non-finites primitives.
message NonFinites {
optional float f_nan = 1;
optional float f_pinf = 2;
optional float f_ninf = 3;
optional double d_nan = 4;
optional double d_pinf = 5;
optional double d_ninf = 6;
}
// Test message for holding repeated primitives.
message Repeats {
repeated bool r_bool = 1;
repeated int32 r_int32 = 2;
repeated int64 r_int64 = 3;
repeated uint32 r_uint32 = 4;
repeated uint64 r_uint64 = 5;
repeated sint32 r_sint32 = 6;
repeated sint64 r_sint64 = 7;
repeated float r_float = 8;
repeated double r_double = 9;
repeated string r_string = 10;
repeated bytes r_bytes = 11;
}
// Test message for holding enums and nested messages.
message Widget {
enum Color {
RED = 0;
GREEN = 1;
BLUE = 2;
};
optional Color color = 1;
repeated Color r_color = 2;
optional Simple simple = 10;
repeated Simple r_simple = 11;
optional Repeats repeats = 20;
repeated Repeats r_repeats = 21;
}
message Maps {
map<int64, string> m_int64_str = 1;
map<bool, Simple> m_bool_simple = 2;
}
message MsgWithOneof {
oneof union {
string title = 1;
int64 salary = 2;
string Country = 3;
string home_address = 4;
MsgWithRequired msg_with_required = 5;
}
}
message Real {
optional double value = 1;
extensions 100 to max;
}
extend Real {
optional string name = 124;
}
message Complex {
extend Real {
optional Complex real_extension = 123;
}
optional double imaginary = 1;
extensions 100 to max;
}
message KnownTypes {
optional google.protobuf.Any an = 14;
optional google.protobuf.Duration dur = 1;
optional google.protobuf.Struct st = 12;
optional google.protobuf.Timestamp ts = 2;
optional google.protobuf.ListValue lv = 15;
optional google.protobuf.Value val = 16;
optional google.protobuf.DoubleValue dbl = 3;
optional google.protobuf.FloatValue flt = 4;
optional google.protobuf.Int64Value i64 = 5;
optional google.protobuf.UInt64Value u64 = 6;
optional google.protobuf.Int32Value i32 = 7;
optional google.protobuf.UInt32Value u32 = 8;
optional google.protobuf.BoolValue bool = 9;
optional google.protobuf.StringValue str = 10;
optional google.protobuf.BytesValue bytes = 11;
}
// Test messages for marshaling/unmarshaling required fields.
message MsgWithRequired {
required string str = 1;
}
message MsgWithIndirectRequired {
optional MsgWithRequired subm = 1;
map<string, MsgWithRequired> map_field = 2;
repeated MsgWithRequired slice_field = 3;
}
message MsgWithRequiredBytes {
required bytes byts = 1;
}
message MsgWithRequiredWKT {
required google.protobuf.StringValue str = 1;
}
extend Real {
optional MsgWithRequired extm = 125;
}

View File

@@ -0,0 +1,34 @@
package main
import (
"flag"
"os"
"github.com/golang/glog"
"go-common/app/tool/protoc-gen-bm/codegenerator"
"go-common/app/tool/protoc-gen-bm/genbm"
"go-common/app/tool/protoc-gen-bm/util"
)
var useJSONPB bool
func init() {
flag.BoolVar(&useJSONPB, "jsonpb", false, "use jsonpb instead of std library, NOTE: jsonpb very slow")
}
func main() {
flag.Parse()
req, err := codegenerator.ParseRequest(os.Stdin)
if err != nil {
glog.Fatal(err)
}
if err = util.ParseParamSetFlag(req.GetParameter(), flag.CommandLine); err != nil {
glog.Fatal(err)
}
g := genbm.New(useJSONPB)
resp, err := g.Generate(req)
if err = codegenerator.WriteResponse(os.Stdout, resp, err); err != nil {
glog.Fatal(err)
}
}

View File

@@ -0,0 +1,40 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["style_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = [
"param.go",
"style.go",
],
importpath = "go-common/app/tool/protoc-gen-bm/util",
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,27 @@
package util
import (
"flag"
"fmt"
"strings"
)
// ParseParamSetFlag parse param from a=b,c=d
func ParseParamSetFlag(param string, fset *flag.FlagSet) (err error) {
if param == "" {
return nil
}
args := strings.Split(param, ",")
for _, arg := range args {
spec := strings.SplitN(arg, "=", 2)
if len(spec) == 2 {
err = fset.Set(spec[0], spec[1])
} else {
err = fset.Set(spec[0], "")
}
if err != nil {
return fmt.Errorf("set flag error: %s", err)
}
}
return nil
}

View File

@@ -0,0 +1,34 @@
package util
// CamelCase convert to Camel-Case
func CamelCase(name string) string {
if len(name) == 0 {
return name
}
if name[0] == '_' {
return name
}
input := []byte(name)
ret := make([]byte, 0, len(input))
toUpper := func(c byte) byte {
if 'a' <= c && c <= 'z' {
c -= 32
}
return c
}
ret = append(ret, toUpper(input[0]))
underline := false
for _, c := range input[1:] {
switch {
case c == '_':
underline = true
default:
if underline {
c = toUpper(c)
}
ret = append(ret, c)
underline = false
}
}
return string(ret)
}

View File

@@ -0,0 +1,32 @@
package util
import "testing"
func TestCamelCase(t *testing.T) {
type args struct {
name string
}
tests := []struct {
name string
args args
want string
}{
{
name: "test1",
args: args{name: "_test"},
want: "_test",
},
{
name: "test2",
args: args{name: "hello_world"},
want: "HelloWorld",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := CamelCase(tt.args.name); got != tt.want {
t.Errorf("CamelCase() = %v, want %v", got, tt.want)
}
})
}
}