Working with Advanced Proto Features

1. Implementing Custom Options

Example: Defining and using a custom field option

import "google/protobuf/descriptor.proto";
extend google.protobuf.FieldOptions {
  string format = 50001;
}
message User {
  string email = 1 [(format) = "email"];
}
Extension TargetUse
FileOptionsFile-wide config
MessageOptionsPer-message
FieldOptionsPer-field (validation, docs)
MethodOptionsPer-RPC (HTTP rules, auth)

2. Using Message Extensions

NoteDetail
Statusproto2 feature; in proto3 only for *Options
Modern alternativeUse Any or oneof

3. Working with Unknown Fields

BehaviorDetail
DefaultPreserved by parser, re-emitted on serialize
Access (Go)m.ProtoReflect().GetUnknown()
PurposeForward compatibility across versions

4. Using Proto Reflection API

Example: Iterate fields via reflection (Go)

m := &User{Id: "u1", Email: "a@b.com"}
m.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
    fmt.Println(fd.Name(), v.Interface())
    return true
})
InterfacePurpose
ProtoReflect()Access descriptors at runtime
DescriptorSchema introspection
FieldDescriptorPer-field metadata

5. Implementing Dynamic Messages

API (Go)Purpose
dynamicpb.NewMessage(desc)Build messages without generated code
protoregistry.GlobalFilesLookup descriptors at runtime
Use caseGeneric proxies, transcoders, gateways

6. Using JSON Mapping

ProtoJSON
snake_case fieldcamelCase by default (user_iduserId)
enum valueString name; integer also accepted
bytesBase64
Timestamp/DurationRFC 3339 / duration string
Default fieldsOmitted unless EmitUnpopulated=true

7. Configuring Field Behavior

Annotation (google.api.field_behavior)Meaning
REQUIREDServer rejects if unset
OPTIONALMay be unset
OUTPUT_ONLYServer-populated, client cannot set
INPUT_ONLYSent on input, not returned
IMMUTABLECannot be changed after creation

8. Using API Annotations

Example: HTTP mapping annotation

import "google/api/annotations.proto";
service UserService {
  rpc GetUser(GetUserRequest) returns (User) {
    option (google.api.http) = { get: "/v1/users/{id}" };
  }
}
OptionPurpose
google.api.httpREST mapping (grpc-gateway)
google.api.method_signatureClient method overloads

9. Implementing Proto Validation

ToolPurpose
protoc-gen-validate (PGV) LEGACYOriginal validator
protovalidate MODERNCEL-based, language-agnostic successor
Buf pluginbuf.build/bufbuild/protovalidate

10. Using Service Options

Example: Default host + OAuth scope

service UserService {
  option (google.api.default_host) = "users.googleapis.com";
  option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/users";
}
OptionPurpose
deprecated = trueMark service/method deprecated
idempotency_levelNO_SIDE_EFFECTS / IDEMPOTENT