### Basic go-fuzz Setup and Execution Source: https://github.com/protocolbuffers/protobuf-go/blob/master/internal/fuzz/README.md Installs go-fuzz and go114-fuzz-build, navigates to the fuzzer directory, builds the fuzzer, and starts the fuzzing process. ```sh $ go install github.com/dvyukov/go-fuzz/go-fuzz $ go install github.com/mdempsky/go114-fuzz-build $ cd internal/fuzz/{fuzzer} $ go114-fuzz-build google.golang.org/protobuf/internal/fuzz/{fuzzer} $ go-fuzz ``` -------------------------------- ### Custom Protoc Plugin Example Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md A complete example of a custom protoc plugin written in Go, demonstrating file generation and custom code for messages. ```go package main import ( "flag" "fmt" "google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/proto" ) func main() { var flags flag.FlagSet customFlag := flags.Bool("custom", false, "Enable custom generation") opts := &protogen.Options{ ParamFunc: flags.Set, } opts.Run(func(gen *protogen.Plugin) error { for _, f := range gen.Files { if !f.Generate { continue } // Generate a file g := gen.NewGeneratedFile( f.GeneratedFilenamePrefix + "_custom.go", f.GoImportPath, ) g.P("// Code generated by custom plugin") g.P("package ", f.GoPackageName) g.P() // Generate code for messages for _, msg := range f.Messages { g.P("func (m *", msg.GoIdent.Name, ") Custom() string {") g.In() g.P("return \"custom\"") g.Out() g.P("}") } } return nil }) } ``` -------------------------------- ### Protoc Command with Custom Options Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Example of invoking protoc with custom plugin options, demonstrating how to pass key-value pairs for configuration. ```bash protoc --custom_out=. --custom_opt=custom=true,other=value myfile.proto ``` -------------------------------- ### Creating and Accessing Value Instances Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Example of creating a string and an integer `Value` using constructor functions and accessing their underlying types. ```go val := protoreflect.ValueOfString("test") fmt.Println(val.String()) // "test" val = protoreflect.ValueOfInt32(42) fmt.Println(val.Int32()) // 42 ``` -------------------------------- ### Instantiate ProtoMessage Reflective View Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Example of how to get the reflective view of a protobuf message instance. ```go msg := &pb.MyMessage{Name: "test"} reflect := msg.ProtoReflect() ``` -------------------------------- ### Example Generated File Creation and Writing Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Demonstrates creating a new generated file, setting package declaration, importing necessary packages, and writing a Go struct definition. ```go g := gen.NewGeneratedFile("example.pb.go", "example.com/pkg") g.P("package ", f.GoPackageName) g.P() g.P("import (") g.In() g.Import("proto", "google.golang.org/protobuf/proto") g.Out() g.P(")") g.P() g.P("// Generated message") g.P("type MyMessage struct {") g.In() g.P("Name string") g.Out() g.P("}") ``` -------------------------------- ### Main Function for Protoc Plugin Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Example of how to set up and run a protoc plugin using protogen. It iterates through generated files and creates a new Go file for each. ```go func main() { opts := &protogen.Options{ ParamFunc: paramFunc, } opts.Run(func(gen *protogen.Plugin) error { for _, f := range gen.Files { if !f.Generate { continue } // Generate code for file f g := gen.NewGeneratedFile(f.GeneratedFilenamePrefix + ".pb.go", f.GoImportPath) g.P("// Generated code for", f.Desc.Path()) } return nil }) } ``` -------------------------------- ### Map Field Manipulation Example Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Shows how to set a value in a map field and then iterate over its entries using the Map interface. ```go field := msg.ProtoReflect().Mutable(fd) mapVal := field.Map() mapVal.Set(protoreflect.MapKey(protoreflect.ValueOfString("key")), protoreflect.ValueOfInt32(42)) mapVal.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { fmt.Printf("%v = %v\n", k, v) return true }) ``` -------------------------------- ### Usage Example: Lookup and Instantiate Message Type Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-registry.md Demonstrates how to look up a well-known message type by name using GlobalTypes and then create a new instance of that message type. ```go package main import ( "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/descriptorpb" ) func main() { // Lookup a well-known message type mt, err := protoregistry.GlobalTypes.FindMessageByName("google.protobuf.Any") if err != nil { log.Fatal(err) } // Create a new instance msg := mt.New() // Work with the message fmt.Printf("Type: %s\n", msg.Descriptor().FullName()) } ``` -------------------------------- ### FullName Type Example Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Demonstrates how to use the Parent() and Name() methods of the FullName type to extract parts of a fully-qualified name. ```go fullName := protoreflect.FullName("google.protobuf.Any") parent := fullName.Parent() // "google.protobuf" shortName := fullName.Name() // "Any" ``` -------------------------------- ### Create google.protobuf.Wrapper Types Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Provides examples of creating wrapper types like StringValue and Int32Value from the 'wrapperspb' package, useful for optional scalar fields in proto3. ```go import "google.golang.org/protobuf/types/known/wrapperspb" msg := &wrapperspb.StringValue{Value: "hello"} msg := &wrapperspb.Int32Value{Value: 42} ``` -------------------------------- ### Setup Git Pre-Push Hook for Testing Source: https://github.com/protocolbuffers/protobuf-go/blob/master/CONTRIBUTING.md Set up a Git pre-push hook to automatically run tests before submitting changes to Gerrit. This ensures code quality and catches regressions early. ```bash $ (cd protobuf/.git/hooks && echo -e '#!/bin/bash ./test.bash' > pre-push && chmod a+x pre-push) ``` -------------------------------- ### Create Dynamic Message from File Descriptor Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-dynamic.md Demonstrates how to create a dynamic message when you have a protobuf file descriptor but no generated Go code. It involves loading the descriptor, converting it, getting the message descriptor, and then creating the dynamic message. ```go // Load file descriptor (e.g., from descriptor set) fileDesc := &descriptorpb.FileDescriptorProto{ Name: proto.String("myfile.proto"), Package: proto.String("mypackage"), // ... field definitions ... } // Convert to file descriptor fd, _ := protodesc.NewFile(fileDesc, protoregistry.GlobalFiles) // Get message descriptor from file md := fd.Messages().ByName("MyMessage") // Create dynamic message msg := dynamicpb.NewMessage(md) // Populate fields fields := md.Fields() for i := 0; i < fields.Len(); i++ { field := fields.Get(i) msg.Set(field, protoreflect.ValueOfString("value")) } // Marshal to wire format data, _ := proto.Marshal(msg.Interface()) ``` -------------------------------- ### Creating Messages from File Descriptor Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-dynamic.md Demonstrates how to create a dynamic protobuf message when you have a file descriptor but no generated Go code. This involves loading the descriptor, converting it, getting the message descriptor, and then creating the dynamic message. ```APIDOC ## Creating Messages from File Descriptor ### Description When you have a protobuf file descriptor but no generated Go code, you can use `dynamicpb` to create messages. ### Example ```go // Load file descriptor (e.g., from descriptor set) fileDesc := &descriptorpb.FileDescriptorProto{ Name: proto.String("myfile.proto"), Package: proto.String("mypackage"), // ... field definitions ... } // Convert to file descriptor fd, _ := protodesc.NewFile(fileDesc, protoregistry.GlobalFiles) // Get message descriptor from file md := fd.Messages().ByName("MyMessage") // Create dynamic message msg := dynamicpb.NewMessage(md) // Populate fields fields := md.Fields() for i := 0; i < fields.Len(); i++ { field := fields.Get(i) msg.Set(field, protoreflect.ValueOfString("value")) } // Marshal to wire format data, _ := proto.Marshal(msg.Interface()) ``` ``` -------------------------------- ### Protocol Buffer Text Format Syntax Examples Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/encoding-text.md Illustrates the syntax for scalar fields, repeated fields, nested messages, enum fields, oneof fields, and map fields in Protocol Buffer text format. ```text name: "example" count: 42 flag: true amount: 3.14 bytes_field: "binary\x00data" ``` ```text tags: "first" tags: "second" tags: "third" ``` ```text nested_message: { inner_field: "value" inner_count: 123 } ``` ```text status: "ACTIVE" status: 1 ``` ```text choice: { option_a: "value" } ``` ```text config: { key: "setting1" value: "value1" } config: { key: "setting2" value: "value2" } ``` -------------------------------- ### Get current time from google.protobuf.Timestamp Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Shows how to obtain the current time as a google.protobuf.Timestamp and convert it to a standard Go time.Time object. Requires importing 'timestamppb'. ```go import ( "google.golang.org/protobuf/types/known/timestamppb" ) now := timestamppb.Now() t := now.AsTime() ``` -------------------------------- ### Manipulating Message Fields via Reflection Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Demonstrates checking field existence, getting field values, setting field values, and iterating over populated fields of a protobuf message using its reflective view. ```go msg := &pb.MyMessage{} reflect := msg.ProtoReflect() // Check field existence if reflect.Has(field) { val := reflect.Get(field) } // Set field reflect.Set(field, protoreflect.ValueOfString("test")) // Iterate fields reflect.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { fmt.Printf("%s = %v\n", fd.Name(), v) return true }) ``` -------------------------------- ### Manipulating Repeated Fields via Reflection Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Example of accessing a repeated field as a list, iterating through its elements, and appending a new element using the `List` interface. ```go field := msg.ProtoReflect().Mutable(fd) list := field.List() for i := 0; i < list.Len(); i++ { val := list.Get(i) } list.Append(protoreflect.ValueOfString("new")) ``` -------------------------------- ### Create and Marshal google.protobuf.Any Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Demonstrates how to create a google.protobuf.Any message by marshaling another protobuf message into bytes and assigning it to the Any type's Value field. Requires importing 'anypb' and 'wrapperspb'. ```go import ( "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/wrapperspb" ) msg := &wrapperspb.StringValue{Value: "test"} any := &anypb.Any{ TypeUrl: "type.googleapis.com/google.protobuf.StringValue", } if data, err := proto.Marshal(msg); err == nil { any.Value = data } ``` -------------------------------- ### Get Size of Encoded Protocol Buffer Fixed64 Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/encoding-wire.md Returns the fixed size (8 bytes) for encoding a 64-bit fixed value. ```go func SizeFixed64() int ``` -------------------------------- ### Get Size of Encoded Protocol Buffer Fixed32 Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/encoding-wire.md Returns the fixed size (4 bytes) for encoding a 32-bit fixed value. ```go func SizeFixed32() int ``` -------------------------------- ### Provide User-Friendly Initialization Error Messages Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/errors.md Shows how to present a more user-friendly message to the user when `proto.CheckInitialized` returns an error, indicating missing required fields. ```go if err := proto.CheckInitialized(msg); err != nil { fmt.Printf("Message incomplete. Missing required fields: %v\n", err) } ``` -------------------------------- ### Invoking Custom Plugin with Protoc Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Demonstrates how to invoke a custom protoc plugin using the protoc command-line tool, including passing custom options. ```bash protoc \ --custom_out=. \ --custom_opt=custom=true \ --custom_opt=other=value \ myfile.proto ``` -------------------------------- ### Get Size of Encoded Protocol Buffer Varint Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/encoding-wire.md Returns the size in bytes required to encode a varint. Useful for buffer sizing. ```go func SizeVarint(v uint64) int ``` ```go size := protowire.SizeVarint(42) // 1 byte size := protowire.SizeVarint(16384) // 3 bytes ``` -------------------------------- ### Create and convert google.protobuf.Duration Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Illustrates creating a google.protobuf.Duration from a Go time.Duration and converting it back. Requires importing 'durationpb' and 'time'. ```go import ( "google.golang.org/protobuf/types/known/durationpb" "time" ) dur := durationpb.New(5 * time.Second) d := dur.AsDuration() ``` -------------------------------- ### Get Size of Encoded Protocol Buffer Tag Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/encoding-wire.md Returns the size in bytes of an encoded field tag. This can be used for pre-allocating buffers. ```go func SizeTag(num Number) int ``` ```go tagSize := protowire.SizeTag(5) // Usually 1 byte for small field numbers ``` -------------------------------- ### Get Size of Encoded Protocol Buffer Bytes Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/encoding-wire.md Returns the size in bytes needed to encode length-delimited bytes, including the length prefix. ```go func SizeBytes(v []byte) int ``` -------------------------------- ### Create a google.protobuf.FieldMask Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Demonstrates creating a google.protobuf.FieldMask with specific paths, used for indicating which fields to update in partial operations. Requires importing 'fieldmaskpb'. ```go import "google.golang.org/protobuf/types/known/fieldmaskpb" // Update only name and age fields mask := &fieldmaskpb.FieldMask{ Paths: []string{"name", "age"}, } ``` -------------------------------- ### Access and Populate Well-Known Types Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-dynamic.md Demonstrates how to access and populate fields of well-known Google protobuf types, such as 'google.protobuf.Any', using their descriptors and dynamic message capabilities. ```go // Common well-known types "google.protobuf.Any" "google.protobuf.Timestamp" "google.protobuf.Duration" "google.protobuf.Struct" "google.protobuf.Value" "google.protobuf.Empty" "google.protobuf.FieldMask" "google.protobuf.StringValue" "google.protobuf.Int32Value" "google.protobuf.Int64Value" // ... and others ``` ```go anyType, _ := protoregistry.GlobalTypes.FindMessageByName("google.protobuf.Any") anyMsg := anyType.New() // Populate Any message anyMsg.Set( anyMsg.Descriptor().Fields().ByName("type_url"), protoreflect.ValueOfString("type.googleapis.com/google.protobuf.StringValue"), ) ``` -------------------------------- ### FullName Type Definition Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Represents a fully-qualified name of a Protocol Buffer type, such as 'google.protobuf.Any'. It provides methods to get the parent name and the short name. ```go type FullName string // e.g., "google.protobuf.Any" func (n FullName) Parent() FullName func (n FullName) Name() Name func (n FullName) IsValid() bool ``` -------------------------------- ### Create an empty google.protobuf.Empty message Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Shows how to return an empty google.protobuf.Empty message, typically used for functions that don't return specific data. Requires importing 'emptypb'. ```go import "google.golang.org/protobuf/types/known/emptypb" func DoSomething() (*emptypb.Empty, error) { // Perform action return &emptypb.Empty{}, nil } ``` -------------------------------- ### List Interface Definition Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/types.md Defines the 'List' interface for a reflective view over a repeated field. It supports operations like getting, setting, appending, and truncating elements. ```go type List interface { Len() int Get(index int) Value Set(index int, Value) Append(Value) AppendMutable() Value Truncate(length int) NewElement() Value IsValid() bool } ``` -------------------------------- ### Create a google.protobuf.Struct Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Demonstrates the creation of a google.protobuf.Struct, which represents a JSON-like object with fields mapped to structpb.Value types. Requires importing 'structpb'. ```go import ( "google.golang.org/protobuf/types/known/structpb" ) s := &structpb.Struct{ Fields: map[string]*structpb.Value{ "name": structpb.NewStringValue("Alice"), "age": structpb.NewNumberValue(30), }, } ``` -------------------------------- ### Compare Protobuf Messages with protocmp Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/errors.md Illustrates how to use `cmp.Diff` with `protocmp.Transform` to find differences between two Protocol Buffer messages. Mismatches are reported as a string. ```go if diff := cmp.Diff(want, got, protocmp.Transform()); diff != "" { t.Errorf("Mismatch:\n%s", diff) } ``` -------------------------------- ### Map Interface Definition Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/types.md Defines the 'Map' interface for a reflective view over a map field. It allows operations such as ranging over key-value pairs, checking for keys, getting, setting, and clearing entries. ```go type Map interface { Len() int Range(f func(MapKey, Value) bool) Has(MapKey) bool Get(MapKey) Value Set(MapKey, Value) Clear(MapKey) NewValue() Value IsValid() bool } ``` -------------------------------- ### Manual Wire Format Testing with protopack Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/testing.md Test the manual wire format encoding and decoding of Protocol Buffer messages using the protopack package. This is useful for low-level verification of message serialization. ```go func TestWireFormat(t *testing.T) { // Manually construct a wire-format message want := &pb.MyMessage{ Value: 42, Name: "test", } data, _ := proto.Marshal(want) // Manually decode to verify wire format manualData := protopack.Message{ protopack.Field{1, protopack.Varint(42)}, protopack.Field{2, protopack.String("test")}, }.Bytes() if !bytes.Equal(data, manualData) { t.Error("wire format mismatch") } } ``` -------------------------------- ### Custom ParamFunc for Protoc Plugin Options Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Configure custom protoc plugins to accept command-line options using ParamFunc, allowing dynamic behavior based on provided values. ```go opts := &protogen.Options{ ParamFunc: func(name, value string) error { switch name { case "custom": customEnabled = (value == "true") return nil default: return fmt.Errorf("unknown option: %s", name) } }, } opts.Run(func(gen *protogen.Plugin) error { // Use customEnabled flag }) ``` -------------------------------- ### Map Interface Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md The `Map` interface provides methods to interact with a map field in a Protocol Buffer message. It allows checking the size, iterating over entries, getting and setting values, clearing entries, and creating new zero values for map entries. ```APIDOC ## Map Interface The reflective view over a map field. ### Methods - **Len()** (int): Returns the number of entries in the map. - **Range(f func(MapKey, Value) bool)**: Iterates over the key-value pairs in the map. The provided function `f` is called for each entry. If `f` returns `false`, iteration stops. - **Has(k MapKey)** (bool): Checks if the map contains an entry with the given key `k`. - **Get(k MapKey)** (Value): Retrieves the value associated with the key `k`. If the key is not found, it returns the zero value for the map's value type. - **Set(k MapKey, v Value)**: Sets the value `v` for the key `k` in the map. If an entry with key `k` already exists, its value is updated. - **Clear(k MapKey)**: Removes the entry associated with the key `k` from the map. - **NewValue()** (Value): Creates and returns a new, zero-initialized value of the map's value type. - **IsValid()** (bool): Checks if the map interface is valid and represents an actual map field. ### Example ```go field := msg.ProtoReflect().Mutable(fd) mapVal := field.Map() mapVal.Set(protoreflect.MapKey(protoreflect.ValueOfString("key")), protoreflect.ValueOfInt32(42)) mapVal.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { fmt.Printf("%v = %v\n", k, v) return true }) ``` ``` -------------------------------- ### Plugin Execution Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Executes the plugin's main logic by running a provided function with the Plugin instance. ```go func (opts Options) Run(f func(*Plugin) error) ``` -------------------------------- ### MarshalOptions Configuration Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/proto-core.md Configurable options for marshaling protobuf messages. Use Deterministic to ensure consistent byte output and AllowPartial to permit messages with missing required fields. ```go opts := proto.MarshalOptions{ Deterministic: true, AllowPartial: true, } data, err := opts.Marshal(msg) ``` -------------------------------- ### Access Well-Known Types from Protoregistry in Go Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Demonstrates how to find and create instances of well-known types from the global type registry in Go. This is useful for dynamic type handling. ```go import "google.golang.org/protobuf/reflect/protoregistry" // Lookup by name mt, err := protoregistry.GlobalTypes.FindMessageByName("google.protobuf.Any") if err != nil { log.Fatal(err) } // Create instance msg := mt.New() ``` -------------------------------- ### Converting Between Message Types Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-dynamic.md Shows how to create instances of any registered message type dynamically without static dependencies. This is achieved by finding the message type by name and then creating a new instance. ```APIDOC ## Converting Between Message Types ### Description Create instances of any registered message type without static dependencies. ### Example ```go func createMessageOfType(typeName string) (proto.Message, error) { mt, err := protoregistry.GlobalTypes.FindMessageByName( protoreflect.FullName(typeName)) if err != nil { return nil, err } return mt.New().Interface(), nil } // Usage anyMsg, _ := createMessageOfType("google.protobuf.Any") timestampMsg, _ := createMessageOfType("google.protobuf.Timestamp") ``` ``` -------------------------------- ### NewGeneratedFile Method Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Creates a new file to be generated by the plugin, specifying the output filename and the Go import path for the package. ```go func (p *Plugin) NewGeneratedFile(name string, importPath GoImportPath) *GeneratedFile ``` -------------------------------- ### Clone Go Protocol Buffers Repository Source: https://github.com/protocolbuffers/protobuf-go/blob/master/CONTRIBUTING.md Clone the Go Protocol Buffers source code from its official repository. ```bash $ git clone https://go.googlesource.com/protobuf ``` -------------------------------- ### Create Dynamic Protobuf Message from Descriptor Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-dynamic.md Use protodesc.NewFile to convert a FileDescriptorProto into a File descriptor, then use dynamicpb.NewMessage to create a dynamic message from a message descriptor. ```go import "google.golang.org/protobuf/reflect/protodesc" import "google.golang.org/protobuf/types/descriptorpb" import "google.golang.org/protobuf/reflect/protoregistry" import "google.golang.org/protobuf/types/dynamicpb" fileDesc, err := protodesc.NewFile( &descriptorpb.FileDescriptorProto{ // ... descriptor definition ... }, protoregistry.GlobalFiles, ) // Get message descriptor md := fileDesc.Messages().ByName("MyMessage") // Create dynamic message msg := dynamicpb.NewMessage(md) ``` -------------------------------- ### JSON Encoding and Decoding in Go Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/INDEX.md Utilize the `protojson` package for marshaling messages to JSON and unmarshaling JSON back into messages. Import 'google.golang.org/protobuf/encoding/protojson'. Options for pretty-printing are available. ```Go import "google.golang.org/protobuf/encoding/protojson" // Encode to JSON jsonData, _ := protojson.Marshal(msg) // Pretty-printed opts := protojson.MarshalOptions{Multiline: true} prettyJSON, _ := opts.Marshal(msg) // Decode from JSON msg2 := &pb.MyMessage{} protojson.Unmarshal(jsonData, msg2) ``` -------------------------------- ### FileDescriptor Interface Definition Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Describes a Protocol Buffer file (.proto file). It provides access to the file's path, package name, imports, and definitions of enums, messages, extensions, and services. ```go type FileDescriptor interface { Descriptor Path() string Package() FullName Imports() FileImports Enums() EnumDescriptors Messages() MessageDescriptors Extensions() ExtensionDescriptors Services() ServiceDescriptors SourceLocations() SourceLocations } ``` -------------------------------- ### Pretty-Print Text Format Output Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Configure Text Format MarshalOptions for pretty-printed output with multiline formatting and indentation. This improves the readability of the text format representation. ```go // Pretty-printed text opts := prototext.MarshalOptions{ Multiline: true, Indent: " ", } ``` -------------------------------- ### Options Struct for Protogen Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Defines the configuration options for protogen code generation, including handlers for parameters, import path rewriting, and feature set defaults. ```go type Options struct { ParamFunc func(name, value string) error ImportRewriteFunc func(GoImportPath) GoImportPath FeatureSetDefaults *descriptorpb.FeatureSetDefaults InternalStripForEditionsDiff *bool DefaultAPILevel gofeaturespb.GoFeatures_APILevel } ``` -------------------------------- ### Handling Protobuf Extensions in Go (proto2) Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/INDEX.md Manage protobuf extensions (specific to proto2 syntax) using functions like `HasExtension`, `GetExtension`, `SetExtension`, `ClearExtension`, and `RangeExtensions` from the 'google.golang.org/protobuf/proto' package. ```Go import "google.golang.org/protobuf/proto" // Check extension if proto.HasExtension(msg, myExtension) { val := proto.GetExtension(msg, myExtension) } // Set extension proto.SetExtension(msg, myExtension, value) // Clear extension proto.ClearExtension(msg, myExtension) // Iterate extensions proto.RangeExtensions(msg, func(xt protoreflect.ExtensionType, v any) bool { fmt.Printf("%s = %v\n", xt, v) return true }) ``` -------------------------------- ### Evolution of proto.Unmarshal Function Signature Source: https://github.com/protocolbuffers/protobuf-go/blob/master/README.md Shows the historical changes in the `proto.Unmarshal` function signature from 2008 to 2012, illustrating API evolution in Go. ```go // 2007/09/25 - Conception of Go // 2008/11/12 export func UnMarshal(r io.Read, pb_e reflect.Empty) *os.Error // 2008/11/13 export func UnMarshal(buf *[]byte, pb_e reflect.Empty) *os.Error // 2008/11/24 export func UnMarshal(buf *[]byte, pb_e interface{}) *os.Error // 2008/12/18 export func UnMarshal(buf []byte, pb_e interface{}) *os.Error // 2009/01/20 func UnMarshal(buf []byte, pb_e interface{}) *os.Error // 2009/04/17 func UnMarshal(buf []byte, pb_e interface{}) os.Error // 2009/05/22 func Unmarshal(buf []byte, pb_e interface{}) os.Error // 2011/11/03 func Unmarshal(buf []byte, pb_e interface{}) error // 2012/03/28 - Release of Go 1 // 2012/06/12 func Unmarshal(buf []byte, pb Message) error ``` -------------------------------- ### Manual Protobuf Message Construction with Field Helpers Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/testing.md Construct complex protobuf messages manually using protopack.Field and various helper functions like Varint, String, and Message for detailed wire format manipulation in tests. ```go // Manual construction of a protobuf message data := protopack.Message{ protopack.Field{1, protopack.Varint(42)}, // int32 field protopack.Field{2, protopack.String("hello")}, // string field protopack.Field{3, protopack.Message( // nested message protopack.Field{1, protopack.Varint(99)}, )}, }.Bytes() ``` -------------------------------- ### Identify Registration Conflicts with Warn Policy Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Troubleshoot registration conflicts by setting the GOLANG_PROTOBUF_REGISTRATION_CONFLICT environment variable to 'warn' and filtering output for conflict messages. ```bash GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn go run main.go 2>&1 | grep -i conflict ``` -------------------------------- ### Import Package Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Imports a Go package for use in the generated file, optionally with an alias. ```go func (g *GeneratedFile) Import(alias string, importPath GoImportPath) ``` -------------------------------- ### Value Constructor Functions Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-core.md Provides a set of functions for creating `Value` instances from various Go types, including a generic `ValueOf` function. ```go func ValueOf(v any) Value func ValueOfBool(v bool) Value func ValueOfInt32(v int32) Value func ValueOfInt64(v int64) Value func ValueOfUint32(v uint32) Value func ValueOfUint64(v uint64) Value func ValueOfFloat32(v float32) Value func ValueOfFloat64(v float64) Value func ValueOfString(v string) Value func ValueOfBytes(v []byte) Value func ValueOfEnum(v EnumNumber) Value func ValueOfMessage(v Message) Value func ValueOfList(v List) Value func ValueOfMap(v Map) Value ``` -------------------------------- ### Dynamic Message Creation in Go Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/INDEX.md Create and manipulate protobuf messages at runtime using dynamic types from `google.golang.org/protobuf/types/dynamicpb`. This requires obtaining the message descriptor first, typically from `protoregistry`. ```Go import "google.golang.org/protobuf/types/dynamicpb" // Get descriptor mt, _ := protoregistry.GlobalTypes.FindMessageByName("package.Message") md := mt.Descriptor() // Create message at runtime msg := dynamicpb.NewMessage(md) // Use like any other message msg.Set(field, protoreflect.ValueOfString("value")) data, _ := proto.Marshal(msg.Interface()) ``` -------------------------------- ### Define Text Format Marshal Options Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/types.md Configure options for text format marshaling, such as formatting with newlines, emitting ASCII, and including unknown fields. Used with prototext.Marshal() and MarshalOptions.Marshal(). ```go type MarshalOptions struct { Multiline bool Indent string EmitASCII bool AllowPartial bool EmitUnknown bool Resolver interface { ... } } ``` -------------------------------- ### Testing Protobuf Messages with Go Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/INDEX.md Compare protobuf messages in tests using `google.golang.org/protobuf/testing/protocmp` with the `github.com/google/go-cmp/cmp` library. This provides detailed diffs for mismatches. ```Go import ( "github.com/google/go-cmp/cmp" "google.golang.org/protobuf/testing/protocmp" ) func TestMessage(t *testing.T) { want := &pb.MyMessage{Name: "test"} got := getActualMessage() if diff := cmp.Diff(want, got, protocmp.Transform()); diff != "" { t.Errorf("Mismatch:\n%s", diff) } } ``` -------------------------------- ### New Plugin Creation Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Creates a new Plugin instance from a CodeGeneratorRequest, utilizing the configured Options. ```go func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) ``` -------------------------------- ### Plugin Type Definition Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Represents a protoc plugin invocation, holding the request, file information, and supported features/editions. ```go type Plugin struct { Request *pluginpb.CodeGeneratorRequest Files []*File FilesByPath map[string]*File SupportedFeatures uint64 SupportedEditionsMinimum descriptorpb.Edition SupportedEditionsMaximum descriptorpb.Edition } ``` -------------------------------- ### Optional Scalar Constructors (Proto2) Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/proto-core.md Provides helper functions to create pointers to scalar values, commonly used for optional fields in proto2 messages. Each function takes a value and returns a pointer to a new instance of that value's type. ```go func Bool(v bool) *bool func Int32(v int32) *int32 func Int64(v int64) *int64 func Uint32(v uint32) *uint32 func Uint64(v uint64) *uint64 func Float32(v float32) *float32 func Float64(v float64) *float64 func String(v string) *string msg := &pb.MyMessage{ OptionalName: proto.String("test"), OptionalCount: proto.Int32(42), OptionalFlag: proto.Bool(true), } ``` -------------------------------- ### Define Binary Marshal Options Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/types.md Configure options for binary marshaling, such as allowing partial messages or ensuring deterministic output. Used with proto.Marshal() and MarshalOptions.Marshal(). ```go type MarshalOptions struct { AllowPartial bool Deterministic bool UseCachedSize bool } ``` -------------------------------- ### Handle Configuration Errors with Custom Resolver Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/errors.md Illustrates handling `protoregistry.NotFound` errors when unmarshaling with `protojson`, which can occur if a custom `Resolver` cannot find a required type. Ensure the `Resolver` is correctly configured. ```go opts := protojson.UnmarshalOptions{ Resolver: customResolver, } if err := opts.Unmarshal(data, msg); err != nil { if errors.Is(err, protoregistry.NotFound) { log.Printf("Type resolution failed (check Resolver): %v", err) } } ``` -------------------------------- ### File Type Definition Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Represents a proto file being processed, containing its descriptor, generated filename prefix, Go package information, and whether to generate code. ```go type File struct { Desc protoreflect.FileDescriptor GeneratedFilenamePrefix string GoImportPath GoImportPath GoPackageName GoPackageName Generate bool Messages []*Message Enums []*Enum Services []*Service } ``` -------------------------------- ### Define JSON Marshal Options Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/types.md Configure options for JSON marshaling, such as formatting with newlines, using proto field names, and emitting unpopulated or default-valued fields. Used with protojson.Marshal() and MarshalOptions.Marshal(). ```go type MarshalOptions struct { Multiline bool Indent string AllowPartial bool UseProtoNames bool UseEnumNumbers bool EmitUnpopulated bool EmitDefaultValues bool Resolver interface { ... } } ``` -------------------------------- ### Find File Descriptor by Path Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-registry.md Looks up a file descriptor by its path. Returns the file descriptor or a NotFound error. ```go fd, err := protoregistry.GlobalFiles.FindFileByPath("google/protobuf/any.proto") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Handling Unknown Types at Runtime Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-dynamic.md Illustrates how to process protobuf messages at runtime when their types are not known at compile time. This involves looking up the message type by URL and then unmarshalling the data into a dynamically created message. ```APIDOC ## Handling Unknown Types at Runtime ### Description When receiving messages whose types are not known at compile time, you can use `dynamicpb` to handle them. ### Example ```go func processMessage(typeURL string, data []byte) error { // Lookup type by URL mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL) if err != nil { // Try dynamic lookup fullName := protoreflect.FullName(strings.TrimPrefix(typeURL, "type.googleapis.com/")) mt, err = protoregistry.GlobalTypes.FindMessageByName(fullName) if err != nil { return err } } // Create and unmarshal message msg := mt.New() if err := proto.Unmarshal(data, msg.Interface()); err != nil { return err } // Process message msg.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { fmt.Printf("%s = %v\n", fd.Name(), v) return true }) return nil } ``` ``` -------------------------------- ### File Type Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Represents a proto file being processed by the plugin, containing its descriptor, generated filename prefix, Go import path, package name, and generation status. ```APIDOC ## File Type ### Description Represents a proto file. ### Fields - **Desc** (protoreflect.FileDescriptor) - File descriptor. - **GeneratedFilenamePrefix** (string) - Prefix for generated output files. - **GoImportPath** (GoImportPath) - Go import path. - **GoPackageName** (GoPackageName) - Go package name. - **Generate** (bool) - Whether to generate code for this file. - **Messages** ([]*Message) - Message types defined in file. - **Enums** ([]*Enum) - Enum types defined in file. - **Services** ([]*Service) - Service definitions. ``` -------------------------------- ### Set Registration Conflict Policy to Warn Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Build your Go program with warnings enabled for protobuf type registration conflicts. This is useful for debugging multiple proto file versions. ```bash GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn go run main.go ``` -------------------------------- ### Internal API for Build-Time Stripping for Edition Testing Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Utilize the internal InternalStripForEditionsDiff option for testing proto2/proto3 to editions migration. Note: This is an internal API and subject to change. ```go opts := &protogen.Options{ InternalStripForEditionsDiff: &stripForEditions, } ``` -------------------------------- ### Basic Message Serialization in Go Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/INDEX.md Use `proto.Marshal` to encode a protobuf message into binary format and `proto.Unmarshal` to decode it back into a message object. Ensure you import the 'google.golang.org/protobuf/proto' package. ```Go import "google.golang.org/protobuf/proto" msg := &pb.MyMessage{Name: "test", Value: 42} // Encode data, err := proto.Marshal(msg) // Decode msg2 := &pb.MyMessage{} err = proto.Unmarshal(data, msg2) ``` -------------------------------- ### Iterate Over Registered Files Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/reflect-registry.md Iterates over all registered file descriptors, calling a provided function for each. The iteration stops if the callback function returns false. ```go protoregistry.GlobalFiles.RangeFiles(func(fd protoreflect.FileDescriptor) bool { fmt.Printf("File: %s\n", fd.Path()) return true }) ``` -------------------------------- ### Pre-calculate Message Size for Marshaling Performance Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Optimize message marshaling performance by pre-calculating the message size and using the UseCachedSize option. ```go size := proto.Size(msg) opts := proto.MarshalOptions{UseCachedSize: true} data, err := opts.Marshal(msg) ``` -------------------------------- ### Emit All Fields in JSON Output Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Configure JSON MarshalOptions to include all fields, even unpopulated ones. This ensures that the JSON representation is complete. ```go // Include all fields (even unpopulated) opts := protojson.MarshalOptions{ EmitUnpopulated: true, } ``` -------------------------------- ### google.protobuf.Any Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/types-known.md Wraps an arbitrary message with a type URL for dynamic message handling. It includes fields for TypeUrl and Value. ```APIDOC ## google.protobuf.Any ### Description Wraps an arbitrary message with a type URL for dynamic message handling. ### Fields - **TypeUrl** (string) - Type URL (format: "type.googleapis.com/package.MessageName") - **Value** ([]byte) - Serialized message bytes ### Usage Example ```go import ( "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/wrapperspb" ) msg := &wrapperspb.StringValue{Value: "test"} any := &anypb.Any{ TypeUrl: "type.googleapis.com/google.protobuf.StringValue", } if data, err := proto.Marshal(msg); err == nil { any.Value = data } ``` ``` -------------------------------- ### Pretty-Print JSON Output Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Configure JSON MarshalOptions for pretty-printed output with multiline formatting and indentation. This enhances readability of the generated JSON. ```go // Pretty-printed JSON opts := protojson.MarshalOptions{ Multiline: true, Indent: " ", } ``` -------------------------------- ### Manually Construct Protobuf Wire Format Message Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/testing.md Use protopack.Message to manually construct a protobuf wire-format message from field definitions. This is helpful for low-level testing of encoding and decoding logic. ```go import "google.golang.org/protobuf/testing/protopack" data := protopack.Message{ protopack.Field{1, protopack.Varint(42)}, protopack.Field{2, protopack.String("test")}, }.Bytes() ``` -------------------------------- ### Marshal Messages with Unknown Fields Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/errors.md Demonstrates how to include unknown fields when marshaling a message to JSON using `protojson.MarshalOptions{EmitUnknown: true}`. This is useful for debugging or inspecting data that might contain unexpected fields. ```go opts := protojson.MarshalOptions{EmitUnknown: true} data, _ := opts.Marshal(msg) fmt.Println(string(data)) // See what unknown fields exist ``` -------------------------------- ### protopack.Message Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/testing.md Manually constructs a wire-format protobuf message from field definitions. ```APIDOC ## protopack.Message ### Description Manually constructs a wire-format message from field definitions. ### Method Signature ```go func Message(fields ...field) []byte ``` ### Example ```go import "google.golang.org/protobuf/testing/protopack" data := protopack.Message{ protopack.Field{1, protopack.Varint(42)}, protopack.Field{2, protopack.String("test")}, }.Bytes() ``` ``` -------------------------------- ### Define Binary Unmarshal Options Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/types.md Configure options for binary unmarshaling, including merging into existing messages, allowing partial data, and discarding unknown fields. Used with proto.Unmarshal() and UnmarshalOptions.Unmarshal(). ```go type UnmarshalOptions struct { Merge bool AllowPartial bool DiscardUnknown bool Resolver interface { ... } RecursionLimit int NoLazyDecoding bool } ``` -------------------------------- ### Run Protoc Plugin Function Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Executes a plugin function, processing a CodeGeneratorRequest from stdin and writing a CodeGeneratorResponse to stdout. Errors from the plugin function are reported in the response, while I/O or parsing errors cause program exit. ```go func (opts Options) Run(f func(*Plugin) error) ``` -------------------------------- ### Check Message Initialization Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/proto-core.md Verifies if all required fields within a Protocol Buffer message have been set. Returns an error if any required field is missing, otherwise returns nil. Useful for validating messages before sending or processing. ```go func CheckInitialized(m Message) error msg := &pb.MyMessage{} if err := proto.CheckInitialized(msg); err != nil { log.Fatal("Message missing required fields:", err) } ``` -------------------------------- ### Define JSON Unmarshal Options Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/types.md Configure options for JSON unmarshaling, including allowing partial data, discarding unknown fields, and setting recursion limits. Used with protojson.Unmarshal() and UnmarshalOptions.Unmarshal(). ```go type UnmarshalOptions struct { AllowPartial bool DiscardUnknown bool Resolver interface { ... } RecursionLimit int } ``` -------------------------------- ### GoPackageName Type Definition Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/compiler-protogen.md Represents a Go package name as a string. ```go type GoPackageName string ``` -------------------------------- ### protocmp.MessageOptions Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/testing.md Returns comparison options for protobuf messages with lenient default comparison, treating empty/nil fields and unknown fields as equal. ```APIDOC ## protocmp.MessageOptions ### Description Returns comparison options for protobuf messages with lenient default comparison. ### Method Signature ```go func MessageOptions() []cmp.Option ``` ### Lenient features - Treats empty and nil message fields as equal - Treats empty and nil list/map fields as equal - Ignores unknown fields by default ``` -------------------------------- ### Marshal Well-Known Types to JSON Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/encoding-json.md Demonstrates marshaling Protocol Buffer messages containing Google Well-Known Types like Timestamp and Duration into their standard JSON representations. ```go msg := &pb.MyMessage{ Timestamp: timestamppb.Now(), Duration: &durationpb.Duration{Seconds: 300}, } data, _ := protojson.Marshal(msg) // {"timestamp":"2024-01-02T15:04:05Z","duration":"300s"} ``` -------------------------------- ### Marshal Message to Binary Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/proto-core.md Converts a protobuf message into its wire-format binary encoding. Ensure the message does not have missing required fields. ```go msg := &pb.MyMessage{Name: "example", Value: 42} data, err := proto.Marshal(msg) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Marshal Message Deterministically Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/configuration.md Configure MarshalOptions for deterministic serialization. This ensures reproducible output, which is beneficial for hashing and caching. ```go // Ensure deterministic serialization opts := proto.MarshalOptions{Deterministic: true} data, err := opts.Marshal(msg) ``` -------------------------------- ### Unmarshal Partial or Streaming Data Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/errors.md Demonstrates using `proto.UnmarshalOptions{AllowPartial: true}` to handle scenarios with incomplete or streaming data. This option prevents errors when some fields might be missing. ```go // For partial/streaming data opts := proto.UnmarshalOptions{AllowPartial: true} if err := opts.Unmarshal(chunk, msg); err != nil { log.Printf("Failed to unmarshal chunk: %v", err) } ``` -------------------------------- ### MarshalOptions.Size Source: https://github.com/protocolbuffers/protobuf-go/blob/master/_autodocs/api-reference/proto-core.md Calculates the size in bytes of the wire-format encoding of a protobuf message using configurable options. This allows for size estimation with specific marshaling behaviors applied. ```APIDOC ## MarshalOptions.Size ### Description Calculate size using these options. ### Method POST ### Endpoint /proto.MarshalOptions/Size ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (MarshalOptions) - Required - The marshaling options. - **AllowPartial** (bool) - Optional - Allow marshaling messages with missing required fields. - **Deterministic** (bool) - Optional - Ensure same message always serializes to same bytes within binary. - **UseCachedSize** (bool) - Optional - Reuse size from a previous Size() call (with identical options). - **m** (Message) - Required - The protobuf message. ### Request Example ```json { "options": { "Deterministic": true }, "m": { "Name": "test" } } ``` ### Response #### Success Response (200) - **size** (int) - The size in bytes of the wire-format encoding. #### Response Example ```json { "size": 15 } ``` ERROR HANDLING: - An error is returned if size calculation fails. ```