-
Notifications
You must be signed in to change notification settings - Fork 9
/
any.go
47 lines (36 loc) · 1.14 KB
/
any.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package protos
import (
"log"
"reflect"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/known/anypb"
)
const TypeUrlPrefix = "type.googleapis.com/"
func NewFromType[V proto.Message]() V {
var m V
return reflect.New(reflect.TypeOf(m).Elem()).Interface().(V)
}
func TypeUrl[V proto.Message]() string {
return TypeUrlForInstance(NewFromType[V]())
}
func TypeUrlForInstance(m proto.Message) string {
return TypeUrlPrefix + string(m.ProtoReflect().Descriptor().FullName())
}
func WrapAnysOrDie(srcs ...protoreflect.ProtoMessage) []*anypb.Any {
var out []*anypb.Any
for _, src := range srcs {
out = append(out, WrapAnyOrDie(src))
}
return out
}
func WrapAnyOrDie(src protoreflect.ProtoMessage) *anypb.Any {
any, err := anypb.New(src)
if err != nil {
log.Fatalf("Failed to wrap %s proto in an Any proto: %s", src.ProtoReflect().Descriptor().FullName(), err)
}
return any
}