Documentation ¶
Overview ¶
Package proto converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler.
A summary of the properties of the protocol buffer interface for a protocol buffer variable v:
- Names are turned from camel_case to CamelCase for export.
- There are no methods on v to set fields; just treat them as structure fields.
- There are getters that return a field's value if set, and return the field's default value if unset. The getters work even if the receiver is a nil message.
- The zero value for a struct is its correct initialization state. All desired fields must be set before marshaling.
- A Reset() method will restore a protobuf struct to its zero state.
- Non-repeated fields are pointers to the values; nil means unset. That is, optional or required field int32 f becomes F *int32.
- Repeated fields are slices.
- Helper functions are available to aid the setting of fields. msg.Foo = proto.String("hello") // set field
- Constants are defined to hold the default values of all fields that have them. They have the form Default_StructName_FieldName. Because the getter methods handle defaulted values, direct use of these constants should be rare.
- Enums are given type names and maps from names to values. Enum values are prefixed by the enclosing message's name, or by the enum's type name if it is a top-level enum. Enum types have a String method, and a Enum method to assist in message construction.
- Nested messages, groups and enums have type names prefixed with the name of the surrounding message type.
- Extensions are given descriptor names that start with E_, followed by an underscore-delimited list of the nested messages that contain it (if any) followed by the CamelCased name of the extension field itself. HasExtension, ClearExtension, GetExtension and SetExtension are functions for manipulating extensions.
- Oneof field sets are given a single field in their message, with distinguished wrapper types for each possible field value.
- Marshal and Unmarshal are functions to encode and decode the wire format.
When the .proto file specifies `syntax="proto3"`, there are some differences:
- Non-repeated fields of non-message type are values instead of pointers.
- Getters are only generated for message and oneof fields.
- Enum types do not get an Enum method.
The simplest way to describe this is to see an example. Given file test.proto, containing
package example; enum FOO { X = 17; } message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } oneof union { int32 number = 6; string name = 7; } }
The resulting file, test.pb.go, is:
package example import proto "github.com/golang/protobuf/proto" import math "math" type FOO int32 const ( FOO_X FOO = 17 ) var FOO_name = map[int32]string{ 17: "X", } var FOO_value = map[string]int32{ "X": 17, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data) if err != nil { return err } *x = FOO(value) return nil } type Test struct { Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` // Types that are valid to be assigned to Union: // *Test_Number // *Test_Name Union isTest_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Test) Reset() { *m = Test{} } func (m *Test) String() string { return proto.CompactTextString(m) } func (*Test) ProtoMessage() {} type isTest_Union interface { isTest_Union() } type Test_Number struct { Number int32 `protobuf:"varint,6,opt,name=number"` } type Test_Name struct { Name string `protobuf:"bytes,7,opt,name=name"` } func (*Test_Number) isTest_Union() {} func (*Test_Name) isTest_Union() {} func (m *Test) GetUnion() isTest_Union { if m != nil { return m.Union } return nil } const Default_Test_Type int32 = 77 func (m *Test) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *Test) GetType() int32 { if m != nil && m.Type != nil { return *m.Type } return Default_Test_Type } func (m *Test) GetOptionalgroup() *Test_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } type Test_OptionalGroup struct { RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` } func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } func (m *Test_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } func (m *Test) GetNumber() int32 { if x, ok := m.GetUnion().(*Test_Number); ok { return x.Number } return 0 } func (m *Test) GetName() string { if x, ok := m.GetUnion().(*Test_Name); ok { return x.Name } return "" } func init() { proto.RegisterEnum("example.FOO", FOO_name, FOO_value) }
To create and play with a Test object:
package main import ( "log" "github.com/golang/protobuf/proto" pb "./example.pb" ) func main() { test := &pb.Test{ Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &pb.Test_OptionalGroup{ RequiredField: proto.String("good bye"), }, Union: &pb.Test_Name{"fred"}, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &pb.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } // Use a type switch to determine which oneof was set. switch u := test.Union.(type) { case *pb.Test_Number: // u.Number contains the number. case *pb.Test_Name: // u.Name contains the string. } // etc. }
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func CamelCase(s string) string
- func CamelCaseSlice(elem []string) string
- func ClearAllExtensions(pb Message)
- func ClearExtension(pb Message, extension *ExtensionDesc)
- func CompactText(w io.Writer, pb Message) error
- func CompactTextString(pb Message) string
- func DecodeVarint(buf []byte) (x uint64, n int)
- func DynField(gen *Generator, message *Descriptor, field *descriptor.FieldDescriptorProto, ...) reflect.StructField
- func DynStruct(desc *descriptor.FileDescriptorProto) []*reflect.Type
- func EncodeVarint(x uint64) []byte
- func EnumName(m map[int32]string, v int32) string
- func EnumValueMap(enumType string) map[string]int32
- func Equal(a, b Message) bool
- func Float32(v float32) *float32
- func Float64(v float64) *float64
- func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error)
- func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error)
- func GetFileDescriptor(filename string) []byte
- func HasExtension(pb Message, extension *ExtensionDesc) bool
- func Int(v int) *int32
- func Int32(v int32) *int32
- func Int64(v int64) *int64
- func Marshal(pb interface{}) ([]byte, error)
- func MarshalMessageSet(exts interface{}) ([]byte, error)
- func MarshalMessageSetJSON(exts interface{}) ([]byte, error)
- func MarshalText(w io.Writer, pb Message) error
- func MarshalTextString(pb Message) string
- func Merge(dst, src Message)
- func MessageName(x Message) string
- func MessageType(name string) reflect.Type
- func ParseSchema(schema string) (descriptor.FileDescriptorProto, error)
- func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32)
- func RegisterExtension(desc *ExtensionDesc)
- func RegisterFile(filename string, fileDescriptor []byte)
- func RegisterMessageSetType(m Message, fieldNum int32, name string)
- func RegisterPlugin(p Plugin)
- func RegisterType(x Message, name string)
- func RegisterUniquePackageName(pkg string, f *FileDescriptor) string
- func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc
- func SetDefaults(pb Message)
- func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error
- func SetRawExtension(base Message, id int32, b []byte)
- func Size(pb Message) (n int)
- func SizeVarint(x uint64) int
- func String(v string) *string
- func Uint32(v uint32) *uint32
- func Uint64(v uint64) *uint64
- func Unmarshal(buf []byte, pb Message) error
- func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error)
- func UnmarshalMerge(buf []byte, pb Message) error
- func UnmarshalMessageSet(buf []byte, exts interface{}) error
- func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error
- func UnmarshalText(s string, pb Message) error
- type Buffer
- func (p *Buffer) Bytes() []byte
- func (p *Buffer) DebugPrint(s string, b []byte)
- func (p *Buffer) DecodeFixed32() (x uint64, err error)
- func (p *Buffer) DecodeFixed64() (x uint64, err error)
- func (p *Buffer) DecodeGroup(pb Message) error
- func (p *Buffer) DecodeMessage(pb Message) error
- func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error)
- func (p *Buffer) DecodeStringBytes() (s string, err error)
- func (p *Buffer) DecodeVarint() (x uint64, err error)
- func (p *Buffer) DecodeZigzag32() (x uint64, err error)
- func (p *Buffer) DecodeZigzag64() (x uint64, err error)
- func (p *Buffer) EncodeFixed32(x uint64) error
- func (p *Buffer) EncodeFixed64(x uint64) error
- func (p *Buffer) EncodeMessage(pb Message) error
- func (p *Buffer) EncodeRawBytes(b []byte) error
- func (p *Buffer) EncodeStringBytes(s string) error
- func (p *Buffer) EncodeVarint(x uint64) error
- func (p *Buffer) EncodeZigzag32(x uint64) error
- func (p *Buffer) EncodeZigzag64(x uint64) error
- func (p *Buffer) Marshal(pb interface{}) error
- func (p *Buffer) Reset()
- func (p *Buffer) SetBuf(s []byte)
- func (p *Buffer) Unmarshal(pb interface{}) error
- type Descriptor
- type EnumDescriptor
- type Extension
- type ExtensionDesc
- type ExtensionDescriptor
- type ExtensionRange
- type FileDescriptor
- type Generator
- func (g *Generator) BuildTypeNameMap()
- func (g *Generator) CommandLineParameters(parameter string)
- func (g *Generator) DefaultPackageName(obj Object) string
- func (g *Generator) Error(err error, msgs ...string)
- func (g *Generator) Fail(msgs ...string)
- func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor
- func (g *Generator) GenerateAllFiles()
- func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string)
- func (g *Generator) In()
- func (g *Generator) ObjectNamed(typeName string) Object
- func (g *Generator) Out()
- func (g *Generator) P(str ...interface{})
- func (g *Generator) PrintComments(path string) bool
- func (g *Generator) RecordTypeUse(t string)
- func (g *Generator) SetPackageNames()
- func (g *Generator) TypeName(obj Object) string
- func (g *Generator) TypeNameWithPackage(obj Object) string
- func (g *Generator) WrapTypes()
- type ImportedDescriptor
- type Marshaler
- type Message
- type Object
- type OneofProperties
- type ParseError
- type Plugin
- type Properties
- type RequiredNotSetError
- type Stats
- type StructProperties
- type TextMarshaler
- type Unmarshaler
- type XXX_InternalExtensions
Constants ¶
const ( WireVarint = 0 WireFixed64 = 1 WireBytes = 2 WireStartGroup = 3 WireEndGroup = 4 WireFixed32 = 5 )
Constants that identify the encoding of a value on the wire.
const ProtoPackageIsVersion1 = true
ProtoPackageIsVersion1 is referenced from generated protocol buffer files to assert that that code is compatible with this version of the proto package.
const ProtoPackageIsVersion2 = true
ProtoPackageIsVersion2 is referenced from generated protocol buffer files to assert that that code is compatible with this version of the proto package.
Variables ¶
var ( // ErrNil is the error returned if Marshal is called with nil. ErrNil = errors.New("proto: Marshal called with nil") // ErrTooLarge is the error returned if Marshal is called with a // message that encodes to >2GB. ErrTooLarge = errors.New("proto: message encodes to over 2 GB") )
var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
ErrInternalBadWireType is returned by generated code when an incorrect wire type is encountered. It does not get returned to user code.
var ErrMissingExtension = errors.New("proto: missing extension")
ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
var SchemaParseError = errors.New("error parsing schema")
Functions ¶
func Bool ¶
Bool is a helper routine that allocates a new bool value to store v and returns a pointer to it.
func CamelCase ¶
CamelCase returns the CamelCased name. If there is an interior underscore followed by a lower case letter, drop the underscore and convert the letter to upper case. There is a remote possibility of this rewrite causing a name collision, but it's so remote we're prepared to pretend it's nonexistent - since the C++ generator lowercases names, it's extremely unlikely to have two fields with different capitalizations. In short, _my_field_name_2 becomes XMyFieldName_2.
func CamelCaseSlice ¶
CamelCaseSlice is like CamelCase, but the argument is a slice of strings to be joined with "_".
func ClearAllExtensions ¶
func ClearAllExtensions(pb Message)
ClearAllExtensions clears all extensions from pb.
func ClearExtension ¶
func ClearExtension(pb Message, extension *ExtensionDesc)
ClearExtension removes the given extension from pb.
func CompactText ¶
CompactText writes a given protocol buffer in compact text format (one line).
func CompactTextString ¶
CompactTextString is the same as CompactText, but returns the string directly.
func DecodeVarint ¶
DecodeVarint reads a varint-encoded integer from the slice. It returns the integer and the number of bytes consumed, or zero if there is not enough. This is the format for the int32, int64, uint32, uint64, bool, and enum protocol buffer types.
func DynField ¶
func DynField(gen *Generator, message *Descriptor, field *descriptor.FieldDescriptorProto, structs *map[string]*reflect.Type) reflect.StructField
func DynStruct ¶
func DynStruct(desc *descriptor.FileDescriptorProto) []*reflect.Type
warning: we set FileDescriptorProto.Name
func EncodeVarint ¶
EncodeVarint returns the varint encoding of x. This is the format for the int32, int64, uint32, uint64, bool, and enum protocol buffer types. Not used by the package itself, but helpful to clients wishing to use the same encoding.
func EnumName ¶
EnumName is a helper function to simplify printing protocol buffer enums by name. Given an enum map and a value, it returns a useful string.
func EnumValueMap ¶
EnumValueMap returns the mapping from names to integers of the enum type enumType, or a nil if not found.
func Equal ¶
Equal returns true iff protocol buffers a and b are equal. The arguments must both be pointers to protocol buffer structs.
Equality is defined in this way:
- Two messages are equal iff they are the same type, corresponding fields are equal, unknown field sets are equal, and extensions sets are equal.
- Two set scalar fields are equal iff their values are equal. If the fields are of a floating-point type, remember that NaN != x for all x, including NaN. If the message is defined in a proto3 .proto file, fields are not "set"; specifically, zero length proto3 "bytes" fields are equal (nil == {}).
- Two repeated fields are equal iff their lengths are the same, and their corresponding elements are equal. Note a "bytes" field, although represented by []byte, is not a repeated field and the rule for the scalar fields described above applies.
- Two unset fields are equal.
- Two unknown field sets are equal if their current encoded state is equal.
- Two extension sets are equal iff they have corresponding elements that are pairwise equal.
- Two map fields are equal iff their lengths are the same, and they contain the same set of elements. Zero-length map fields are equal.
- Every other combination of things are not equal.
The return value is undefined if a and b are not protocol buffers.
func Float32 ¶
Float32 is a helper routine that allocates a new float32 value to store v and returns a pointer to it.
func Float64 ¶
Float64 is a helper routine that allocates a new float64 value to store v and returns a pointer to it.
func GetExtension ¶
func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error)
GetExtension parses and returns the given extension of pb. If the extension is not present and has no default value it returns ErrMissingExtension.
func GetExtensions ¶
func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error)
GetExtensions returns a slice of the extensions present in pb that are also listed in es. The returned slice has the same length as es; missing extensions will appear as nil elements.
func GetFileDescriptor ¶
FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
func HasExtension ¶
func HasExtension(pb Message, extension *ExtensionDesc) bool
HasExtension returns whether the given extension is present in pb.
func Int ¶
Int is a helper routine that allocates a new int32 value to store v and returns a pointer to it, but unlike Int32 its argument value is an int.
func Int32 ¶
Int32 is a helper routine that allocates a new int32 value to store v and returns a pointer to it.
func Int64 ¶
Int64 is a helper routine that allocates a new int64 value to store v and returns a pointer to it.
func Marshal ¶
Marshal takes the protocol buffer and encodes it into the wire format, returning the data.
func MarshalMessageSet ¶
MarshalMessageSet encodes the extension map represented by m in the message set wire format. It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
func MarshalMessageSetJSON ¶
MarshalMessageSetJSON encodes the extension map represented by m in JSON format. It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
func MarshalText ¶
MarshalText writes a given protocol buffer in text format. The only errors returned are from w.
func MarshalTextString ¶
MarshalTextString is the same as MarshalText, but returns the string directly.
func Merge ¶
func Merge(dst, src Message)
Merge merges src into dst. Required and optional fields that are set in src will be set to that value in dst. Elements of repeated fields will be appended. Merge panics if src and dst are not the same type, or if dst is nil.
func MessageName ¶
MessageName returns the fully-qualified proto name for the given message type.
func MessageType ¶
MessageType returns the message type (pointer to struct) for a named message.
func ParseSchema ¶
func ParseSchema(schema string) (descriptor.FileDescriptorProto, error)
wrapper for CPP proto schema parser
func RegisterEnum ¶
RegisterEnum is called from the generated code to install the enum descriptor maps into the global table to aid parsing text format protocol buffers.
func RegisterExtension ¶
func RegisterExtension(desc *ExtensionDesc)
RegisterExtension is called from the generated code.
func RegisterFile ¶
RegisterFile is called from generated code and maps from the full file name of a .proto file to its compressed FileDescriptorProto.
func RegisterMessageSetType ¶
RegisterMessageSetType is called from the generated code.
func RegisterPlugin ¶
func RegisterPlugin(p Plugin)
RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated. It is typically called during initialization.
func RegisterType ¶
RegisterType is called from generated code and maps from the fully qualified proto name to the type (pointer to struct) of the protocol buffer.
func RegisterUniquePackageName ¶
func RegisterUniquePackageName(pkg string, f *FileDescriptor) string
Create and remember a guaranteed unique package name for this file descriptor. Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and has no file descriptor.
func RegisteredExtensions ¶
func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc
RegisteredExtensions returns a map of the registered extensions of a protocol buffer struct, indexed by the extension number. The argument pb should be a nil pointer to the struct type.
func SetDefaults ¶
func SetDefaults(pb Message)
SetDefaults sets unset protocol buffer fields to their default values. It only modifies fields that are both unset and have defined defaults. It recursively sets default values in any non-nil sub-messages.
func SetExtension ¶
func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error
SetExtension sets the specified extension of pb to the specified value.
func SetRawExtension ¶
SetRawExtension is for testing only.
func SizeVarint ¶
SizeVarint returns the varint encoding size of an integer.
func String ¶
String is a helper routine that allocates a new string value to store v and returns a pointer to it.
func Uint32 ¶
Uint32 is a helper routine that allocates a new uint32 value to store v and returns a pointer to it.
func Uint64 ¶
Uint64 is a helper routine that allocates a new uint64 value to store v and returns a pointer to it.
func Unmarshal ¶
Unmarshal parses the protocol buffer representation in buf and places the decoded result in pb. If the struct underlying pb does not match the data in buf, the results can be unpredictable.
Unmarshal resets pb before starting to unmarshal, so any existing data in pb is always removed. Use UnmarshalMerge to preserve and append to existing data.
func UnmarshalJSONEnum ¶
UnmarshalJSONEnum is a helper function to simplify recovering enum int values from their JSON-encoded representation. Given a map from the enum's symbolic names to its int values, and a byte buffer containing the JSON-encoded value, it returns an int32 that can be cast to the enum type by the caller.
The function can deal with both JSON representations, numeric and symbolic.
func UnmarshalMerge ¶
UnmarshalMerge parses the protocol buffer representation in buf and writes the decoded result to pb. If the struct underlying pb does not match the data in buf, the results can be unpredictable.
UnmarshalMerge merges into existing data in pb. Most code should use Unmarshal instead.
func UnmarshalMessageSet ¶
UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
func UnmarshalMessageSetJSON ¶
UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
func UnmarshalText ¶
UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb before starting to unmarshal, so any existing data in pb is always removed. If a required field is not set and no other error occurs, UnmarshalText returns *RequiredNotSetError.
Types ¶
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
A Buffer is a buffer manager for marshaling and unmarshaling protocol buffers. It may be reused between invocations to reduce memory usage. It is not necessary to use a Buffer; the global functions Marshal and Unmarshal create a temporary Buffer and are fine for most applications.
func NewBuffer ¶
NewBuffer allocates a new Buffer and initializes its internal data to the contents of the argument slice.
func (*Buffer) DebugPrint ¶
DebugPrint dumps the encoded data in b in a debugging format with a header including the string s. Used in testing but made available for general debugging.
func (*Buffer) DecodeFixed32 ¶
DecodeFixed32 reads a 32-bit integer from the Buffer. This is the format for the fixed32, sfixed32, and float protocol buffer types.
func (*Buffer) DecodeFixed64 ¶
DecodeFixed64 reads a 64-bit integer from the Buffer. This is the format for the fixed64, sfixed64, and double protocol buffer types.
func (*Buffer) DecodeGroup ¶
DecodeGroup reads a tag-delimited group from the Buffer.
func (*Buffer) DecodeMessage ¶
DecodeMessage reads a count-delimited message from the Buffer.
func (*Buffer) DecodeRawBytes ¶
DecodeRawBytes reads a count-delimited byte buffer from the Buffer. This is the format used for the bytes protocol buffer type and for embedded messages.
func (*Buffer) DecodeStringBytes ¶
DecodeStringBytes reads an encoded string from the Buffer. This is the format used for the proto2 string type.
func (*Buffer) DecodeVarint ¶
DecodeVarint reads a varint-encoded integer from the Buffer. This is the format for the int32, int64, uint32, uint64, bool, and enum protocol buffer types.
func (*Buffer) DecodeZigzag32 ¶
DecodeZigzag32 reads a zigzag-encoded 32-bit integer from the Buffer. This is the format used for the sint32 protocol buffer type.
func (*Buffer) DecodeZigzag64 ¶
DecodeZigzag64 reads a zigzag-encoded 64-bit integer from the Buffer. This is the format used for the sint64 protocol buffer type.
func (*Buffer) EncodeFixed32 ¶
EncodeFixed32 writes a 32-bit integer to the Buffer. This is the format for the fixed32, sfixed32, and float protocol buffer types.
func (*Buffer) EncodeFixed64 ¶
EncodeFixed64 writes a 64-bit integer to the Buffer. This is the format for the fixed64, sfixed64, and double protocol buffer types.
func (*Buffer) EncodeMessage ¶
EncodeMessage writes the protocol buffer to the Buffer, prefixed by a varint-encoded length.
func (*Buffer) EncodeRawBytes ¶
EncodeRawBytes writes a count-delimited byte buffer to the Buffer. This is the format used for the bytes protocol buffer type and for embedded messages.
func (*Buffer) EncodeStringBytes ¶
EncodeStringBytes writes an encoded string to the Buffer. This is the format used for the proto2 string type.
func (*Buffer) EncodeVarint ¶
EncodeVarint writes a varint-encoded integer to the Buffer. This is the format for the int32, int64, uint32, uint64, bool, and enum protocol buffer types.
func (*Buffer) EncodeZigzag32 ¶
EncodeZigzag32 writes a zigzag-encoded 32-bit integer to the Buffer. This is the format used for the sint32 protocol buffer type.
func (*Buffer) EncodeZigzag64 ¶
EncodeZigzag64 writes a zigzag-encoded 64-bit integer to the Buffer. This is the format used for the sint64 protocol buffer type.
func (*Buffer) Marshal ¶
Marshal takes the protocol buffer and encodes it into the wire format, writing the result to the Buffer.
func (*Buffer) Reset ¶
func (p *Buffer) Reset()
Reset resets the Buffer, ready for marshaling a new protocol buffer.
func (*Buffer) SetBuf ¶
SetBuf replaces the internal buffer with the slice, ready for unmarshaling the contents of the slice.
func (*Buffer) Unmarshal ¶
Unmarshal parses the protocol buffer representation in the Buffer and places the decoded result in pb. If the struct underlying pb does not match the data in the buffer, the results can be unpredictable.
Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
type Descriptor ¶
type Descriptor struct { *descriptor.DescriptorProto // contains filtered or unexported fields }
Descriptor represents a protocol buffer message.
func (*Descriptor) File ¶
func (c *Descriptor) File() *descriptor.FileDescriptorProto
func (*Descriptor) PackageName ¶
func (c *Descriptor) PackageName() string
PackageName is name in the package clause in the generated file.
func (*Descriptor) TypeName ¶
func (d *Descriptor) TypeName() []string
TypeName returns the elements of the dotted type name. The package name is not part of this name.
type EnumDescriptor ¶
type EnumDescriptor struct { *descriptor.EnumDescriptorProto // contains filtered or unexported fields }
EnumDescriptor describes an enum. If it's at top level, its parent will be nil. Otherwise it will be the descriptor of the message in which it is defined.
func (*EnumDescriptor) File ¶
func (c *EnumDescriptor) File() *descriptor.FileDescriptorProto
func (*EnumDescriptor) PackageName ¶
func (c *EnumDescriptor) PackageName() string
PackageName is name in the package clause in the generated file.
func (*EnumDescriptor) TypeName ¶
func (e *EnumDescriptor) TypeName() (s []string)
TypeName returns the elements of the dotted type name. The package name is not part of this name.
type Extension ¶
type Extension struct {
// contains filtered or unexported fields
}
Extension represents an extension in a message.
type ExtensionDesc ¶
type ExtensionDesc struct { ExtendedType Message // nil pointer to the type that is being extended ExtensionType interface{} // nil pointer to the extension type Field int32 // field number Name string // fully-qualified name of extension, for text formatting Tag string // protobuf tag style Filename string // name of the file in which the extension is defined }
ExtensionDesc represents an extension specification. Used in generated code from the protocol compiler.
func ExtensionDescs ¶
func ExtensionDescs(pb Message) ([]*ExtensionDesc, error)
ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing just the Field field, which defines the extension's field number.
type ExtensionDescriptor ¶
type ExtensionDescriptor struct { *descriptor.FieldDescriptorProto // contains filtered or unexported fields }
ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil. Otherwise it will be the descriptor of the message in which it is defined.
func (*ExtensionDescriptor) DescName ¶
func (e *ExtensionDescriptor) DescName() string
DescName returns the variable name used for the generated descriptor.
func (*ExtensionDescriptor) File ¶
func (c *ExtensionDescriptor) File() *descriptor.FileDescriptorProto
func (*ExtensionDescriptor) PackageName ¶
func (c *ExtensionDescriptor) PackageName() string
PackageName is name in the package clause in the generated file.
func (*ExtensionDescriptor) TypeName ¶
func (e *ExtensionDescriptor) TypeName() (s []string)
TypeName returns the elements of the dotted type name. The package name is not part of this name.
type ExtensionRange ¶
type ExtensionRange struct {
Start, End int32 // both inclusive
}
ExtensionRange represents a range of message extensions for a protocol buffer. Used in code generated by the protocol compiler.
type FileDescriptor ¶
type FileDescriptor struct { *descriptor.FileDescriptorProto // contains filtered or unexported fields }
FileDescriptor describes an protocol buffer descriptor file (.proto). It includes slices of all the messages and enums defined within it. Those slices are constructed by WrapTypes.
func (*FileDescriptor) PackageName ¶
func (d *FileDescriptor) PackageName() string
PackageName is the package name we'll use in the generated code to refer to this file.
func (*FileDescriptor) VarName ¶
func (d *FileDescriptor) VarName() string
VarName is the variable name we'll use in the generated code to refer to the compressed bytes of this descriptor. It is not exported, so it is only valid inside the generated package.
type Generator ¶
type Generator struct { *bytes.Buffer Request *plugin.CodeGeneratorRequest // The input. Response *plugin.CodeGeneratorResponse // The output. Param map[string]string // Command-line parameters. PackageImportPath string // Go import path of the package we're generating code for ImportPrefix string // String to prefix to imported package file names. ImportMap map[string]string // Mapping from .proto file name to import path Pkg map[string]string // The names under which we import support packages // contains filtered or unexported fields }
func NewGenerator ¶
func NewGenerator() *Generator
New creates a new generator and allocates the request and response protobufs.
func (*Generator) BuildTypeNameMap ¶
func (g *Generator) BuildTypeNameMap()
BuildTypeNameMap builds the map from fully qualified type names to objects. The key names for the map come from the input data, which puts a period at the beginning. It should be called after SetPackageNames and before GenerateAllFiles.
func (*Generator) CommandLineParameters ¶
CommandLineParameters breaks the comma-separated list of key=value pairs in the parameter (a member of the request protobuf) into a key/value map. It then sets file name mappings defined by those entries.
func (*Generator) DefaultPackageName ¶
DefaultPackageName returns the package name printed for the object. If its file is in a different package, it returns the package name we're using for this file, plus ".". Otherwise it returns the empty string.
func (*Generator) FileOf ¶
func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor
FileOf return the FileDescriptor for this FileDescriptorProto.
func (*Generator) GenerateAllFiles ¶
func (g *Generator) GenerateAllFiles()
GenerateAllFiles generates the output for all the files we're outputting.
func (*Generator) GoType ¶
func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string)
GoType returns a string representing the type name, and the wire type
func (*Generator) ObjectNamed ¶
ObjectNamed, given a fully-qualified input type name as it appears in the input data, returns the descriptor for the message or enum with that name.
func (*Generator) P ¶
func (g *Generator) P(str ...interface{})
P prints the arguments to the generated output. It handles strings and int32s, plus handling indirections because they may be *string, etc.
func (*Generator) PrintComments ¶
PrintComments prints any comments from the source .proto file. The path is a comma-separated list of integers. It returns an indication of whether any comments were printed. See descriptor.proto for its format.
func (*Generator) RecordTypeUse ¶
func (*Generator) SetPackageNames ¶
func (g *Generator) SetPackageNames()
SetPackageNames sets the package name for this run. The package name must agree across all files being generated. It also defines unique package names for all imported files.
func (*Generator) TypeName ¶
TypeName is the printed name appropriate for an item. If the object is in the current file, TypeName drops the package name and underscores the rest. Otherwise the object is from another package; and the result is the underscored package name followed by the item name. The result always has an initial capital.
func (*Generator) TypeNameWithPackage ¶
TypeNameWithPackage is like TypeName, but always includes the package name even if the object is in our own package.
func (*Generator) WrapTypes ¶
func (g *Generator) WrapTypes()
WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos and FileDescriptorProtos into file-referenced objects within the Generator. It also creates the list of files to generate and so should be called before GenerateAllFiles.
type ImportedDescriptor ¶
type ImportedDescriptor struct {
// contains filtered or unexported fields
}
ImportedDescriptor describes a type that has been publicly imported from another file.
func (*ImportedDescriptor) File ¶
func (c *ImportedDescriptor) File() *descriptor.FileDescriptorProto
func (*ImportedDescriptor) PackageName ¶
func (c *ImportedDescriptor) PackageName() string
PackageName is name in the package clause in the generated file.
func (*ImportedDescriptor) TypeName ¶
func (id *ImportedDescriptor) TypeName() []string
type Message ¶
type Message interface { Reset() String() string ProtoMessage() }
Message is implemented by generated protocol buffer messages.
type Object ¶
type Object interface { PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness. TypeName() []string File() *descriptor.FileDescriptorProto }
Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
type OneofProperties ¶
type OneofProperties struct { Type reflect.Type // pointer to generated struct type for this oneof field Field int // struct field number of the containing oneof in the message Prop *Properties }
OneofProperties represents information about a specific field in a oneof.
type ParseError ¶
type ParseError struct { Message string Line int // 1-based line number Offset int // 0-based byte offset from start of input }
func (*ParseError) Error ¶
func (p *ParseError) Error() string
type Plugin ¶
type Plugin interface { // Name identifies the plugin. Name() string // Init is called once after data structures are built but before // code generation begins. Init(g *Generator) // Generate produces the code generated by the plugin for this file, // except for the imports, by calling the generator's methods P, In, and Out. Generate(file *FileDescriptor) // GenerateImports produces the import declarations for this file. // It is called after Generate. GenerateImports(file *FileDescriptor) }
A Plugin provides functionality to add to the output during Go code generation, such as to produce RPC stubs.
type Properties ¶
type Properties struct { Name string // name of the field, for error messages OrigName string // original name before protocol compiler (always set) JSONName string // name to use for JSON; determined by protoc Wire string WireType int Tag int Required bool Optional bool Repeated bool Packed bool // relevant for repeated primitives only Enum string // set for enum types only Default string // default value HasDefault bool // whether an explicit default was provided // contains filtered or unexported fields }
Properties represents the protocol-specific behavior of a single struct field.
func (*Properties) Init ¶
func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField)
Init populates the properties from a protocol buffer struct tag.
func (*Properties) Parse ¶
func (p *Properties) Parse(s string)
Parse populates p by parsing a string in the protobuf struct field tag style.
func (*Properties) String ¶
func (p *Properties) String() string
String formats the properties in the protobuf struct field tag style.
type RequiredNotSetError ¶
type RequiredNotSetError struct {
// contains filtered or unexported fields
}
RequiredNotSetError is the error returned if Marshal is called with a protocol buffer struct whose required fields have not all been initialized. It is also the error returned if Unmarshal is called with an encoded protocol buffer that does not include all the required fields.
When printed, RequiredNotSetError reports the first unset required field in a message. If the field cannot be precisely determined, it is reported as "{Unknown}".
func (*RequiredNotSetError) Error ¶
func (e *RequiredNotSetError) Error() string
type Stats ¶
type Stats struct { Emalloc uint64 // mallocs in encode Dmalloc uint64 // mallocs in decode Encode uint64 // number of encodes Decode uint64 // number of decodes Chit uint64 // number of cache hits Cmiss uint64 // number of cache misses Size uint64 // number of sizes }
Stats records allocation details about the protocol buffer encoders and decoders. Useful for tuning the library itself.
type StructProperties ¶
type StructProperties struct { Prop []*Properties // properties for each field // OneofTypes contains information about the oneof fields in this message. // It is keyed by the original name of a field. OneofTypes map[string]*OneofProperties // contains filtered or unexported fields }
StructProperties represents properties for all the fields of a struct. decoderTags and decoderOrigNames should only be used by the decoder.
func GetProperties ¶
func GetProperties(t reflect.Type) *StructProperties
GetProperties returns the list of properties for the type represented by t. t must represent a generated struct type of a protocol message.
func (*StructProperties) Len ¶
func (sp *StructProperties) Len() int
func (*StructProperties) Less ¶
func (sp *StructProperties) Less(i, j int) bool
func (*StructProperties) Swap ¶
func (sp *StructProperties) Swap(i, j int)
type TextMarshaler ¶
type TextMarshaler struct { Compact bool // use compact text format (one line). ExpandAny bool // expand google.protobuf.Any messages of known types }
TextMarshaler is a configurable text format marshaler.
func (*TextMarshaler) Marshal ¶
func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error
Marshal writes a given protocol buffer in text format. The only errors returned are from w.
func (*TextMarshaler) Text ¶
func (tm *TextMarshaler) Text(pb Message) string
Text is the same as Marshal, but returns the string directly.
type Unmarshaler ¶
Unmarshaler is the interface representing objects that can unmarshal themselves. The method should reset the receiver before decoding starts. The argument points to data that may be overwritten, so implementations should not keep references to the buffer.
type XXX_InternalExtensions ¶
type XXX_InternalExtensions struct {
// contains filtered or unexported fields
}
XXX_InternalExtensions is an internal representation of proto extensions.
Each generated message struct type embeds an anonymous XXX_InternalExtensions field, thus gaining the unexported 'extensions' method, which can be called only from the proto package.
The methods of XXX_InternalExtensions are not concurrency safe in general, but calls to logically read-only methods such as has and get may be executed concurrently.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package proto3_proto is a generated protocol buffer package.
|
Package proto3_proto is a generated protocol buffer package. |