protobuf

module
v1.2.2-0...-076ffe1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 16, 2021 License: BSD-3-Clause

README

fork from gogo/protobuf

支持以下新特性

支持用protobuf协议描述json协议

  • json编码完整支持required、optional字段语义检测;required字段不填序列化/反序列化报错
  • 比用protobuf本身生成更简洁的代码
  • 生成支持json的marshal & unmarshal方法
  • 支持Set方法(主要是解决成员变量为指针类型,需要手动使用&)
  • Set方法支持builder模式

protobuf代码生成更新

  • 支持Set方法(主要是解决成员变量为指针类型,需要手动使用&)
  • Set方法支持builder模式

安装使用

json协议代码生成

  • golang版
      1. go get github.com/buptbill220/protobuf/protoc-gen-gogofmqjson
      1. protoc --gogofmqjson_out=./ xxx.proto
  • python版
      1. go get github.com/buptbill220/protobuf/protoc-gen-pyfmqjson
      1. protoc --pyfmqjson_out=./ xxx.proto

无缝迁移gogo

    1. go get github.com/buptbill220/protobuf/protoc-gen-gogo
    1. go get github.com/buptbill220/protobuf/protoc-gen-gogofast
    1. go get github.com/buptbill220/protobuf/protoc-gen-gofast

protobuf描述json示例

message User {
    required int64 id = 1;
    required string name = 2
    required int32 age = 3;
    optional Occupation occ = 4;
    repeated Occupation occs = 5;
}
message Occupation {
    required int64 id = 1;
    required string industry = 2;
}

// 代表的json结构如下
{
    "id": 123,
    "name": "fangming",
    "age": 18,
    "occ": {"id": 111, "industry": "professor"},
    "occs": [
        {"id": 111, "industry": "professor"},
        {"id": 222, "industry": "engineer"}
    ],
}

代码生产示例

// FmqJsonCode generated by protoc-gen-gogofmqjson. Do NOT EDIT
// Author: fangming
// Email: fangming@bytedance.com
// source: test.proto
// It is generated from these files:
// 	test.proto

// It has these top-level messages:
//== 	User
//== 	Occupation

package test

import (
	encoding_json "encoding/json"
	fmt "fmt"
)

type User struct {
	Id   *int64        `json:"id"`
	Name *string       `json:"name"`
	Age  *int32        `json:"age"`
	Occ  *Occupation   `json:"occ"`
	Occs []*Occupation `json:"occs"`
}

func (m *User) Reset()      { *m = User{} }
func (*User) ProtoMessage() {}

func (m *User) GetId() int64 {
	if m != nil && m.Id != nil {
		return *m.Id
	}
	return 0
}

func (m *User) SetId(v int64) *User {
	if m != nil {
		m.Id = &v
	}
	return m
}

func (m *User) GetName() string {
	if m != nil && m.Name != nil {
		return *m.Name
	}
	return ""
}

func (m *User) SetName(v string) *User {
	if m != nil {
		m.Name = &v
	}
	return m
}

func (m *User) GetAge() int32 {
	if m != nil && m.Age != nil {
		return *m.Age
	}
	return 0
}

func (m *User) SetAge(v int32) *User {
	if m != nil {
		m.Age = &v
	}
	return m
}

func (m *User) GetOcc() *Occupation {
	if m != nil {
		return m.Occ
	}
	return nil
}

func (m *User) SetOcc(v *Occupation) *User {
	if m != nil {
		m.Occ = v
	}
	return m
}

func (m *User) GetOccs() []*Occupation {
	if m != nil {
		return m.Occs
	}
	return nil
}

func (m *User) SetOccs(v []*Occupation) *User {
	if m != nil {
		m.Occs = v
	}
	return m
}

type Occupation struct {
	Id       *int64  `json:"id"`
	Industry *string `json:"industry"`
}

func (m *Occupation) Reset()      { *m = Occupation{} }
func (*Occupation) ProtoMessage() {}

func (m *Occupation) GetId() int64 {
	if m != nil && m.Id != nil {
		return *m.Id
	}
	return 0
}

func (m *Occupation) SetId(v int64) *Occupation {
	if m != nil {
		m.Id = &v
	}
	return m
}

func (m *Occupation) GetIndustry() string {
	if m != nil && m.Industry != nil {
		return *m.Industry
	}
	return ""
}

func (m *Occupation) SetIndustry(v string) *Occupation {
	if m != nil {
		m.Industry = &v
	}
	return m
}

func (m *User) Marshal() ([]byte, error) {
	if m == nil {
		return nil, fmt.Errorf("msg User is nil")
	}
	if err := m.Validate(); err != nil {
		return nil, err
	}
	return encoding_json.Marshal(m)
}

func (m *User) Unmarshal(data []byte) error {
	if m == nil {
		return fmt.Errorf("msg User is nil")
	}
	if err := encoding_json.Unmarshal(data, m); err != nil {
		return err
	}
	if err := m.Validate(); err != nil {
		return err
	}
	return nil
}

func (m *Occupation) Marshal() ([]byte, error) {
	if m == nil {
		return nil, fmt.Errorf("msg Occupation is nil")
	}
	if err := m.Validate(); err != nil {
		return nil, err
	}
	return encoding_json.Marshal(m)
}

func (m *Occupation) Unmarshal(data []byte) error {
	if m == nil {
		return fmt.Errorf("msg Occupation is nil")
	}
	if err := encoding_json.Unmarshal(data, m); err != nil {
		return err
	}
	if err := m.Validate(); err != nil {
		return err
	}
	return nil
}

func (m *User) Validate() error {
	if m == nil {
		return fmt.Errorf("msg User is nil")
	}
	if m.Id == nil {
		return fmt.Errorf("required field User.Id is nil")
	}
	if m.Name == nil {
		return fmt.Errorf("required field User.Name is nil")
	}
	if m.Age == nil {
		return fmt.Errorf("required field User.Age is nil")
	}
	if m.Occ != nil {
		if err := m.Occ.Validate(); err != nil {
			return err
		}
	}
	for _, p := range m.Occs {
		if err := p.Validate(); err != nil {
			return err
		}
	}
	return nil
}

func (m *Occupation) Validate() error {
	if m == nil {
		return fmt.Errorf("msg Occupation is nil")
	}
	if m.Id == nil {
		return fmt.Errorf("required field Occupation.Id is nil")
	}
	if m.Industry == nil {
		return fmt.Errorf("required field Occupation.Industry is nil")
	}
	return nil
}

测试示例

  • test code
import (
	"fmt"
)

func testUser() {
	user := &User{}
	data, err := user.Marshal()
	if err != nil {
		fmt.Printf("1: user marshal err %s\n", err.Error())
	}
	fmt.Printf("1: user marshal data %s\n", string(data))


	data, err = user.SetId(1).Marshal()
	if err != nil {
		fmt.Printf("2: user marshal err %s\n", err.Error())
	}
	fmt.Printf("2: user marshal data %s\n", string(data))

	data, err = user.SetAge(28).Marshal()
	if err != nil {
		fmt.Printf("3: user marshal err %s\n", err.Error())
	}
	fmt.Printf("3: user marshal data %s\n", string(data))

	data, err = user.SetName("fangming").Marshal()
	if err != nil {
		fmt.Printf("4: user marshal err %s\n", err.Error())
	}
	fmt.Printf("4: user marshal data %s\n", string(data))

	occ := &Occupation{}
	occ.SetId(1)
	data, err = user.SetOcc(occ).Marshal()
	if err != nil {
		fmt.Printf("5: user marshal err %s\n", err.Error())
	}
	fmt.Printf("5: user marshal data %s\n", string(data))

	occ.SetIndustry("computer")
	data, err = user.SetOcc(occ).Marshal()
	if err != nil {
		fmt.Printf("6: user marshal err %s\n", err.Error())
	}
	fmt.Printf("6: user marshal data %s\n", string(data))

	occs := []*Occupation{}
	occ = &Occupation{}
	occ.SetId(2)
	occs = append(occs, occ)
	data, err = user.SetOccs(occs).Marshal()
	if err != nil {
		fmt.Printf("7: user marshal err %s\n", err.Error())
	}
	fmt.Printf("7: user marshal data %s\n", string(data))

	occ.SetIndustry("teacher")
	occs = append(occs, occ)
	data, err = user.SetOccs(occs).Marshal()
	if err != nil {
		fmt.Printf("8: user marshal err %s\n", err.Error())
	}
	fmt.Printf("8: user marshal data %s\n", string(data))
}
  • test output
1: user marshal err required field User.Id is nil
1: user marshal data
2: user marshal err required field User.Name is nil
2: user marshal data
3: user marshal err required field User.Name is nil
3: user marshal data
4: user marshal data {"id":1,"name":"fangming","age":28,"occ":null,"occs":null}
5: user marshal err required field Occupation.Industry is nil
5: user marshal data
6: user marshal data {"id":1,"name":"fangming","age":28,"occ":{"id":1,"industry":"computer"},"occs":null}
7: user marshal err required field Occupation.Industry is nil
7: user marshal data
8: user marshal data {"id":1,"name":"fangming","age":28,"occ":{"id":1,"industry":"computer"},"occs":[{"id":2,"industry":"teacher"},{"id":2,"industry":"teacher"}]}

Directories

Path Synopsis
conformance implements the conformance test subprocess protocol as documented in conformance.proto.
conformance implements the conformance test subprocess protocol as documented in conformance.proto.
Package gogoproto provides extensions for protocol buffers to achieve: - fast marshalling and unmarshalling.
Package gogoproto provides extensions for protocol buffers to achieve: - fast marshalling and unmarshalling.
Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
plugin
defaultcheck
The defaultcheck plugin is used to check whether nullable is not used incorrectly.
The defaultcheck plugin is used to check whether nullable is not used incorrectly.
description
The description (experimental) plugin generates a Description method for each message.
The description (experimental) plugin generates a Description method for each message.
embedcheck
The embedcheck plugin is used to check whether embed is not used incorrectly.
The embedcheck plugin is used to check whether embed is not used incorrectly.
enumstringer
The enumstringer (experimental) plugin generates a String method for each enum.
The enumstringer (experimental) plugin generates a String method for each enum.
equal
The equal plugin generates an Equal and a VerboseEqual method for each message.
The equal plugin generates an Equal and a VerboseEqual method for each message.
face
The face plugin generates a function will be generated which can convert a structure which satisfies an interface (face) to the specified structure.
The face plugin generates a function will be generated which can convert a structure which satisfies an interface (face) to the specified structure.
gostring
The gostring plugin generates a GoString method for each message.
The gostring plugin generates a GoString method for each message.
jsonmarshal
The size plugin generates a Size or ProtoSize method for each message.
The size plugin generates a Size or ProtoSize method for each message.
marshalto
The marshalto plugin generates a Marshal and MarshalTo method for each message.
The marshalto plugin generates a Marshal and MarshalTo method for each message.
oneofcheck
The oneofcheck plugin is used to check whether oneof is not used incorrectly.
The oneofcheck plugin is used to check whether oneof is not used incorrectly.
populate
The populate plugin generates a NewPopulated function.
The populate plugin generates a NewPopulated function.
size
The size plugin generates a Size or ProtoSize method for each message.
The size plugin generates a Size or ProtoSize method for each message.
stringer
The stringer plugin generates a String method for each message.
The stringer plugin generates a String method for each message.
testgen
The testgen plugin generates Test and Benchmark functions for each message.
The testgen plugin generates Test and Benchmark functions for each message.
union
The onlyone plugin generates code for the onlyone extension.
The onlyone plugin generates code for the onlyone extension.
unmarshal
The unmarshal plugin generates a Unmarshal method for each message.
The unmarshal plugin generates a Unmarshal method for each message.
validate
The size plugin generates a Size or ProtoSize method for each message.
The size plugin generates a Size or ProtoSize method for each message.
Package proto converts data structures to and from the wire format of protocol buffers.
Package proto converts data structures to and from the wire format of protocol buffers.
protoc-gen-gogo
descriptor
Package descriptor provides functions for obtaining protocol buffer descriptors for generated Go types.
Package descriptor provides functions for obtaining protocol buffer descriptors for generated Go types.
generator
The code generator for the plugin for the Google protocol buffer compiler.
The code generator for the plugin for the Google protocol buffer compiler.
generator/internal/remap
Package remap handles tracking the locations of Go tokens in a source text across a rewrite by the Go formatter.
Package remap handles tracking the locations of Go tokens in a source text across a rewrite by the Go formatter.
grpc
Package grpc outputs gRPC service descriptions in Go code.
Package grpc outputs gRPC service descriptions in Go code.
custom
Package custom contains custom types for test and example purposes.
Package custom contains custom types for test and example purposes.
custom-dash-type
Package custom contains custom types for test and example purposes.
Package custom contains custom types for test and example purposes.
mapdefaults
Package mapdefaults is a generated protocol buffer package.
Package mapdefaults is a generated protocol buffer package.
typedeclimport
Package typedeclimport is a generated protocol buffer package.
Package typedeclimport is a generated protocol buffer package.
typedeclimport/subpkg
Package subpkg is a generated protocol buffer package.
Package subpkg is a generated protocol buffer package.
Package types contains code for interacting with well-known types.
Package types contains code for interacting with well-known types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL