Google's well-known types are a set of standard protocol buffer message types that solve common problems. These types provide standardized representations for time, duration, dynamic messages, JSON-like structures, field masks, and primitive wrapper types.
import (
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/wrapperspb"
"google.golang.org/protobuf/types/known/apipb"
"google.golang.org/protobuf/types/known/sourcecontextpb"
"google.golang.org/protobuf/types/known/typepb"
)The Any message provides a way to embed arbitrary protocol buffer messages as a type-safe tuple of type URL and serialized value.
// Any contains an arbitrary serialized protocol buffer message along with a
// URL that describes the type of the serialized message
type Any struct {
// A URL/resource name that uniquely identifies the type of the serialized
// protocol buffer message. This string must contain at least
// one "/" character. The last segment of the URL's path must represent
// the fully qualified name of the type (as in
// `path/google.protobuf.Duration`). The name should be in a canonical form
// (e.g., leading "." is not accepted).
TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"`
// Must be a valid serialized protocol buffer of the above specified type
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
func (*Any) ProtoMessage()
func (x *Any) ProtoReflect() protoreflect.Message
func (x *Any) Reset()
func (x *Any) String() string
func (*Any) Descriptor() ([]byte, []int) // Deprecated
func (x *Any) GetTypeUrl() string
func (x *Any) GetValue() []byte// New marshals src into a new Any instance
func New(src proto.Message) (*Any, error)
// MarshalFrom marshals src into dst as the underlying message using the
// provided marshal options
func MarshalFrom(dst *Any, src proto.Message, opts proto.MarshalOptions) error// UnmarshalNew unmarshals the underlying message from src into a newly
// created message using a type resolved from the type URL
func UnmarshalNew(src *Any, opts proto.UnmarshalOptions) (dst proto.Message, err error)
// UnmarshalTo unmarshals the underlying message from src into dst
// It reports an error if dst is not of the right message type
func UnmarshalTo(src *Any, dst proto.Message, opts proto.UnmarshalOptions) error// MarshalFrom marshals m into the Any using default marshal options
func (x *Any) MarshalFrom(m proto.Message) error
// UnmarshalTo unmarshals the contents into m
// It resets m before performing the unmarshal operation
func (x *Any) UnmarshalTo(m proto.Message) error
// UnmarshalNew unmarshals the contents into a new instance of the underlying
// message type and returns it
func (x *Any) UnmarshalNew() (proto.Message, error)
// MessageIs reports whether the underlying message is of the specified type
func (x *Any) MessageIs(m proto.Message) bool
// MessageName reports the full name of the underlying message
func (x *Any) MessageName() protoreflect.FullNameUsage example:
// Pack a message into Any
original := &pb.MyMessage{Name: "example"}
any, err := anypb.New(original)
if err != nil {
log.Fatal(err)
}
// Check type
if any.MessageIs(&pb.MyMessage{}) {
// Unpack into known type
msg := &pb.MyMessage{}
if err := any.UnmarshalTo(msg); err != nil {
log.Fatal(err)
}
fmt.Println(msg.Name)
}
// Unpack when type is unknown
msg, err := any.UnmarshalNew()
if err != nil {
log.Fatal(err)
}
switch m := msg.(type) {
case *pb.MyMessage:
fmt.Println("Got MyMessage:", m.Name)
case *pb.OtherMessage:
fmt.Println("Got OtherMessage:", m.Value)
}The Timestamp message represents a specific point in time independent of timezone.
// Timestamp represents a point in time independent of any time zone or
// local calendar, encoded as a count of seconds and fractions of seconds at
// nanosecond resolution
type Timestamp struct {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999 inclusive.
Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
// Has unexported fields.
}
func (*Timestamp) ProtoMessage()
func (x *Timestamp) ProtoReflect() protoreflect.Message
func (x *Timestamp) Reset()
func (x *Timestamp) String() string
func (*Timestamp) Descriptor() ([]byte, []int) // Deprecated
func (x *Timestamp) GetSeconds() int64
func (x *Timestamp) GetNanos() int32// New constructs a new Timestamp from the provided time.Time
func New(t time.Time) *Timestamp
// Now constructs a new Timestamp from the current time
func Now() *Timestamp// AsTime converts x to a time.Time
func (x *Timestamp) AsTime() time.Time
// IsValid reports whether the timestamp is valid
func (x *Timestamp) IsValid() bool
// CheckValid returns an error if the timestamp is invalid
func (x *Timestamp) CheckValid() errorUsage example:
// Create from time.Time
t := time.Now()
ts := timestamppb.New(t)
// Create current timestamp
ts := timestamppb.Now()
// Convert to time.Time
goTime := ts.AsTime()
// Validate
if err := ts.CheckValid(); err != nil {
log.Fatalf("Invalid timestamp: %v", err)
}
// Use in message
msg := &pb.Event{
Name: "user_login",
Timestamp: timestamppb.Now(),
}The Duration message represents a signed span of time.
// Duration represents a signed, fixed-length span of time represented as
// a count of seconds and fractions of seconds at nanosecond resolution
type Duration struct {
// Signed seconds of the span of time. Must be from -315,576,000,000
// to +315,576,000,000 inclusive.
Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
// Signed fractions of a second at nanosecond resolution of the span
// of time. Durations less than one second are represented with a 0
// `seconds` field and a positive or negative `nanos` field. For durations
// of one second or more, a non-zero value for the `nanos` field must be
// of the same sign as the `seconds` field. Must be from -999,999,999
// to +999,999,999 inclusive.
Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
// Has unexported fields.
}
func (*Duration) ProtoMessage()
func (x *Duration) ProtoReflect() protoreflect.Message
func (x *Duration) Reset()
func (x *Duration) String() string
func (*Duration) Descriptor() ([]byte, []int) // Deprecated
func (x *Duration) GetSeconds() int64
func (x *Duration) GetNanos() int32// New constructs a new Duration from the provided time.Duration
func New(d time.Duration) *Duration
// AsDuration converts x to a time.Duration
func (x *Duration) AsDuration() time.Duration
// IsValid reports whether the duration is valid
func (x *Duration) IsValid() bool
// CheckValid returns an error if the duration is invalid
func (x *Duration) CheckValid() errorUsage example:
// Create from time.Duration
d := 5 * time.Minute
dur := durationpb.New(d)
// Convert to time.Duration
goDuration := dur.AsDuration()
// Use in message
msg := &pb.CachePolicy{
Ttl: durationpb.New(10 * time.Minute),
}The Struct message represents a structured data value similar to a JSON object.
// Struct represents a structured data value, consisting of fields
// which map to dynamically typed values
type Struct struct {
// Unordered map of dynamically typed values
Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields,proto3" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
// Has unexported fields.
}
func (*Struct) ProtoMessage()
func (x *Struct) ProtoReflect() protoreflect.Message
func (x *Struct) Reset()
func (x *Struct) String() string
func (x *Struct) GetFields() map[string]*Value
// Value represents a dynamically typed value which can be either
// null, a number, a string, a boolean, a recursive struct value, or a
// list of values
type Value struct {
// The kind of value
//
// Types that are assignable to Kind:
// *Value_NullValue
// *Value_NumberValue
// *Value_StringValue
// *Value_BoolValue
// *Value_StructValue
// *Value_ListValue
Kind isValue_Kind `protobuf_oneof:"kind"`
// Has unexported fields.
}
func (*Value) ProtoMessage()
func (x *Value) ProtoReflect() protoreflect.Message
func (x *Value) Reset()
func (x *Value) String() string
func (x *Value) GetKind() isValue_Kind
func (x *Value) GetNullValue() NullValue
func (x *Value) GetNumberValue() float64
func (x *Value) GetStringValue() string
func (x *Value) GetBoolValue() bool
func (x *Value) GetStructValue() *Struct
func (x *Value) GetListValue() *ListValue
// ListValue is a wrapper around a repeated field of values
type ListValue struct {
// Repeated field of dynamically typed values
Values []*Value `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"`
// Has unexported fields.
}
func (*ListValue) ProtoMessage()
func (x *ListValue) ProtoReflect() protoreflect.Message
func (x *ListValue) Reset()
func (x *ListValue) String() string
func (x *ListValue) GetValues() []*Value
// NullValue is a singleton enumeration to represent the null value for the
// Value type union
type NullValue int32
const (
// Null value
NullValue_NULL_VALUE NullValue = 0
)// NewStruct constructs a Struct from a general-purpose Go map
// The map keys must be valid UTF-8 and the map values are recursively
// converted using NewValue
func NewStruct(v map[string]interface{}) (*Struct, error)
// NewValue constructs a Value from a general-purpose Go interface
func NewValue(v interface{}) (*Value, error)
// NewList constructs a ListValue from a general-purpose Go slice
// The slice elements are recursively converted using NewValue
func NewList(v []interface{}) (*ListValue, error)
// NewNullValue constructs a new null Value
func NewNullValue() *Value
// NewBoolValue constructs a new boolean Value
func NewBoolValue(v bool) *Value
// NewNumberValue constructs a new number Value
func NewNumberValue(v float64) *Value
// NewStringValue constructs a new string Value
func NewStringValue(v string) *Value
// NewListValue constructs a new list Value
func NewListValue(v *ListValue) *Value
// NewStructValue constructs a new struct Value
func NewStructValue(v *Struct) *Value// AsMap converts x to a general-purpose Go map
func (x *Struct) AsMap() map[string]interface{}
// AsInterface converts x to a general-purpose Go interface
func (x *Value) AsInterface() interface{}
// AsSlice converts x to a general-purpose Go slice
func (x *ListValue) AsSlice() []interface{}Usage example:
// Create from Go map
data := map[string]interface{}{
"name": "Alice",
"age": 30,
"active": true,
"tags": []interface{}{"user", "admin"},
}
s, err := structpb.NewStruct(data)
// Create individual values
val := structpb.NewStringValue("hello")
listVal := structpb.NewListValue(&structpb.ListValue{
Values: []*structpb.Value{
structpb.NewNumberValue(1),
structpb.NewNumberValue(2),
},
})
// Convert to Go types
goMap := s.AsMap()
goInterface := val.AsInterface()The Empty message is used for RPCs that don't require request or response data.
// Empty is an empty message, useful for RPCs that take no request
// or return no response data
type Empty struct {
// Has unexported fields.
}
func (*Empty) ProtoMessage()
func (x *Empty) ProtoReflect() protoreflect.Message
func (x *Empty) Reset()
func (x *Empty) String() stringUsage example:
// Use in service definition
service HealthService {
rpc Ping(emptypb.Empty) returns (emptypb.Empty);
}
// In implementation
func (s *server) Ping(ctx context.Context, _ *emptypb.Empty) (*emptypb.Empty, error) {
return &emptypb.Empty{}, nil
}The FieldMask message represents a set of symbolic field paths for specifying which fields to update.
// FieldMask represents a set of symbolic field paths
type FieldMask struct {
// The set of field mask paths
Paths []string `protobuf:"bytes,1,rep,name=paths,proto3" json:"paths,omitempty"`
// Has unexported fields.
}
func (*FieldMask) ProtoMessage()
func (x *FieldMask) ProtoReflect() protoreflect.Message
func (x *FieldMask) Reset()
func (x *FieldMask) String() string
func (x *FieldMask) GetPaths() []string// New constructs a FieldMask from a list of paths
func New(m proto.Message, paths ...string) (*FieldMask, error)
// Union constructs a FieldMask from the union of the provided masks
func Union(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask
// Intersect constructs a FieldMask from the intersection of the provided masks
func Intersect(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask// IsValid reports whether all the paths are syntactically valid
func (x *FieldMask) IsValid(m proto.Message) error
// Normalize converts the mask to its canonical form where all paths are sorted
// and redundant paths are removed
func (x *FieldMask) Normalize() *FieldMask
// Append appends a list of paths to the mask
func (x *FieldMask) Append(m proto.Message, paths ...string) errorUsage example:
// Create field mask for partial update
mask, err := fieldmaskpb.New(&pb.User{}, "name", "email", "profile.bio")
// Use in update request
updateReq := &pb.UpdateUserRequest{
User: &pb.User{
Name: "Alice",
Email: "alice@example.com",
},
UpdateMask: mask,
}
// Normalize field mask
normalized := mask.Normalize()
// Union of masks
combined := fieldmaskpb.Union(mask1, mask2)Wrapper types provide nullable versions of primitive types for distinguishing between zero values and unset values.
// BoolValue wraps a bool value
type BoolValue struct {
Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// Int32Value wraps an int32 value
type Int32Value struct {
Value int32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// Int64Value wraps an int64 value
type Int64Value struct {
Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// UInt32Value wraps a uint32 value
type UInt32Value struct {
Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// UInt64Value wraps a uint64 value
type UInt64Value struct {
Value uint64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// FloatValue wraps a float value
type FloatValue struct {
Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// DoubleValue wraps a double value
type DoubleValue struct {
Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// StringValue wraps a string value
type StringValue struct {
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// BytesValue wraps a bytes value
type BytesValue struct {
Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}// Bool constructs a BoolValue
func Bool(v bool) *BoolValue
// Int32 constructs an Int32Value
func Int32(v int32) *Int32Value
// Int64 constructs an Int64Value
func Int64(v int64) *Int64Value
// UInt32 constructs a UInt32Value
func UInt32(v uint32) *UInt32Value
// UInt64 constructs a UInt64Value
func UInt64(v uint64) *UInt64Value
// Float constructs a FloatValue
func Float(v float32) *FloatValue
// Double constructs a DoubleValue
func Double(v float64) *DoubleValue
// String constructs a StringValue
func String(v string) *StringValue
// Bytes constructs a BytesValue
func Bytes(v []byte) *BytesValueUsage example:
// Use wrappers for optional fields in proto2 or proto3
msg := &pb.Config{
Timeout: wrapperspb.Int32(30),
Enabled: wrapperspb.Bool(true),
Name: wrapperspb.String("production"),
}
// Check if value is set
if msg.Timeout != nil {
timeout := msg.Timeout.Value
fmt.Println("Timeout:", timeout)
}The API types provide structures for representing API service definitions.
// Api is a light-weight descriptor for an API Interface
type Api struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Methods []*Method `protobuf:"bytes,2,rep,name=methods,proto3" json:"methods,omitempty"`
Options []*typepb.Option `protobuf:"bytes,3,rep,name=options,proto3" json:"options,omitempty"`
Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"`
SourceContext *sourcecontextpb.SourceContext `protobuf:"bytes,5,opt,name=source_context,json=sourceContext,proto3" json:"source_context,omitempty"`
Mixins []*Mixin `protobuf:"bytes,6,rep,name=mixins,proto3" json:"mixins,omitempty"`
Syntax typepb.Syntax `protobuf:"varint,7,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"`
// Has unexported fields.
}
// Method represents an API method
type Method struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
RequestTypeUrl string `protobuf:"bytes,2,opt,name=request_type_url,json=requestTypeUrl,proto3" json:"request_type_url,omitempty"`
RequestStreaming bool `protobuf:"varint,3,opt,name=request_streaming,json=requestStreaming,proto3" json:"request_streaming,omitempty"`
ResponseTypeUrl string `protobuf:"bytes,4,opt,name=response_type_url,json=responseTypeUrl,proto3" json:"response_type_url,omitempty"`
ResponseStreaming bool `protobuf:"varint,5,opt,name=response_streaming,json=responseStreaming,proto3" json:"response_streaming,omitempty"`
Options []*typepb.Option `protobuf:"bytes,6,rep,name=options,proto3" json:"options,omitempty"`
Syntax typepb.Syntax `protobuf:"varint,7,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"`
// Has unexported fields.
}
// Mixin specifies a mixin
type Mixin struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Root string `protobuf:"bytes,2,opt,name=root,proto3" json:"root,omitempty"`
// Has unexported fields.
}The SourceContext message represents information about the source of a protobuf element.
// SourceContext represents information about the source of a protobuf element,
// like the file in which it is defined
type SourceContext struct {
// The path-qualified name of the .proto file that contained the associated
// protobuf element
FileName string `protobuf:"bytes,1,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"`
// Has unexported fields.
}
func (*SourceContext) ProtoMessage()
func (x *SourceContext) ProtoReflect() protoreflect.Message
func (x *SourceContext) Reset()
func (x *SourceContext) String() string
func (x *SourceContext) GetFileName() stringThe Type message describes a protocol buffer message type.
// Type represents a protocol buffer message type
type Type struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Fields []*Field `protobuf:"bytes,2,rep,name=fields,proto3" json:"fields,omitempty"`
Oneofs []string `protobuf:"bytes,3,rep,name=oneofs,proto3" json:"oneofs,omitempty"`
Options []*Option `protobuf:"bytes,4,rep,name=options,proto3" json:"options,omitempty"`
SourceContext *sourcecontextpb.SourceContext `protobuf:"bytes,5,opt,name=source_context,json=sourceContext,proto3" json:"source_context,omitempty"`
Syntax Syntax `protobuf:"varint,6,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"`
Edition string `protobuf:"bytes,7,opt,name=edition,proto3" json:"edition,omitempty"`
// Has unexported fields.
}
// Field represents a single field of a message type
type Field struct {
Kind Field_Kind `protobuf:"varint,1,opt,name=kind,proto3,enum=google.protobuf.Field_Kind" json:"kind,omitempty"`
Cardinality Field_Cardinality `protobuf:"varint,2,opt,name=cardinality,proto3,enum=google.protobuf.Field_Cardinality" json:"cardinality,omitempty"`
Number int32 `protobuf:"varint,3,opt,name=number,proto3" json:"number,omitempty"`
Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"`
TypeUrl string `protobuf:"bytes,6,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"`
OneofIndex int32 `protobuf:"varint,7,opt,name=oneof_index,json=oneofIndex,proto3" json:"oneof_index,omitempty"`
Packed bool `protobuf:"varint,8,opt,name=packed,proto3" json:"packed,omitempty"`
Options []*Option `protobuf:"bytes,9,rep,name=options,proto3" json:"options,omitempty"`
JsonName string `protobuf:"bytes,10,opt,name=json_name,json=jsonName,proto3" json:"json_name,omitempty"`
DefaultValue string `protobuf:"bytes,11,opt,name=default_value,json=defaultValue,proto3" json:"default_value,omitempty"`
// Has unexported fields.
}
// Enum type represents an enumeration type
type Enum struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Enumvalue []*EnumValue `protobuf:"bytes,2,rep,name=enumvalue,proto3" json:"enumvalue,omitempty"`
Options []*Option `protobuf:"bytes,3,rep,name=options,proto3" json:"options,omitempty"`
SourceContext *sourcecontextpb.SourceContext `protobuf:"bytes,4,opt,name=source_context,json=sourceContext,proto3" json:"source_context,omitempty"`
Syntax Syntax `protobuf:"varint,5,opt,name=syntax,proto3,enum=google.protobuf.Syntax" json:"syntax,omitempty"`
Edition string `protobuf:"bytes,6,opt,name=edition,proto3" json:"edition,omitempty"`
// Has unexported fields.
}
// EnumValue is a single value in an enumeration
type EnumValue struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Number int32 `protobuf:"varint,2,opt,name=number,proto3" json:"number,omitempty"`
Options []*Option `protobuf:"bytes,3,rep,name=options,proto3" json:"options,omitempty"`
// Has unexported fields.
}
// Option represents a proto option
type Option struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Value *anypb.Any `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
// Has unexported fields.
}
// Syntax specifies the proto syntax
type Syntax int32
const (
Syntax_SYNTAX_PROTO2 Syntax = 0
Syntax_SYNTAX_PROTO3 Syntax = 1
Syntax_SYNTAX_EDITIONS Syntax = 2
)These well-known types provide standardized solutions for common protocol buffer use cases, enabling interoperability across different languages and systems.