-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmust.go
67 lines (54 loc) · 1.43 KB
/
must.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package testing
import (
"encoding/json"
"time"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/hyperledger-labs/cckit/serialize"
)
// PanicIfError
func PanicIfError(err error) {
if err != nil {
panic(err)
}
}
// MustProtoMarshal marshals proto.Message, panics if error
func MustProtoMarshal(pb proto.Message) []byte {
bb, err := proto.Marshal(pb)
PanicIfError(err)
return bb
}
func MustJSONMarshal(val interface{}) []byte {
bb, err := json.Marshal(val)
PanicIfError(err)
return bb
}
// MustProtoUnmarshal unmarshals proto.Message, panics if error
func MustProtoUnmarshal(bb []byte, pm proto.Message) proto.Message {
p := proto.Clone(pm)
PanicIfError(proto.Unmarshal(bb, p))
return p
}
// MustProtoTimestamp creates proto.Timestamp, panics if error
func MustProtoTimestamp(t time.Time) *timestamp.Timestamp {
return timestamppb.New(t)
}
func MustConvertFromBytes(bb []byte, target interface{}, fromBytesConverter serialize.FromBytesConverter) interface{} {
v, err := fromBytesConverter.FromBytesTo(bb, target)
PanicIfError(err)
return v
}
// MustTime returns Timestamp for date string or panic
func MustTime(s string) *timestamp.Timestamp {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
panic(err)
}
ts, err := ptypes.TimestampProto(t)
if err != nil {
panic(err)
}
return ts
}