generated from dogmatiq/template-go
/
marshal.go
85 lines (68 loc) 路 2.18 KB
/
marshal.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package protomime
import (
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
)
// Marshaler is an interface for marshaling Protocol Buffers messages to a byte
// slice.
type Marshaler interface {
Marshal(proto.Message) ([]byte, error)
}
// Unmarshaler is an interface for unmarshaling Protocol Buffers messages from a
// byte slice.
type Unmarshaler interface {
Unmarshal([]byte, proto.Message) error
}
var (
// BinaryMarshaler is a Marshaler that marshals messages to the binary
// Protocol Buffers encoding.
BinaryMarshaler Marshaler = proto.MarshalOptions{}
// JSONMarshaler is a Marshaler that marshals messages to the JSON Protocol
// Buffers encoding.
JSONMarshaler Marshaler = protojson.MarshalOptions{}
// TextMarshaler is a Marshaler that marshals messages to the text-based
// Protocol Buffers encoding.
TextMarshaler Marshaler = prototext.MarshalOptions{
Multiline: true,
Indent: " ",
}
)
var (
// BinaryUnmarshaler is an Unmarshaler that unmarshals messages from the
// binary Protocol Buffers encoding.
BinaryUnmarshaler Unmarshaler = proto.UnmarshalOptions{}
// JSONUnmarshaler is an Unmarshaler that unmarshals messages from the JSON
// Protocol Buffers encoding.
JSONUnmarshaler Unmarshaler = protojson.UnmarshalOptions{}
// TextUnmarshaler is an Unmarshaler that unmarshals messages from the
// text-based Protocol Buffers encoding.
TextUnmarshaler Unmarshaler = prototext.UnmarshalOptions{}
)
// MarshalerForMediaType returns the marshaler to use for the given media type.
func MarshalerForMediaType(mediaType string) (Marshaler, bool) {
if IsBinary(mediaType) {
return BinaryMarshaler, true
}
if IsJSON(mediaType) {
return JSONMarshaler, true
}
if IsText(mediaType) {
return TextMarshaler, true
}
return nil, false
}
// UnmarshalerForMediaType returns the unmarshaler to use for the given media
// type.
func UnmarshalerForMediaType(mediaType string) (Unmarshaler, bool) {
if IsBinary(mediaType) {
return BinaryUnmarshaler, true
}
if IsJSON(mediaType) {
return JSONUnmarshaler, true
}
if IsText(mediaType) {
return TextUnmarshaler, true
}
return nil, false
}