-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathcodecs.go
More file actions
52 lines (44 loc) · 1.22 KB
/
codecs.go
File metadata and controls
52 lines (44 loc) · 1.22 KB
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
package server
import (
"errors"
"fmt"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
const (
jsonCodec = "json"
)
var (
ErrNotProto = fmt.Errorf("error not proto")
)
// connectCodec implements https://pkg.go.dev/github.com/bufbuild/connect-go#Codec
// by overriding the default implementation with extra option: protojson.MarshalOptions{UseProtoNames: true}
type connectCodec struct {
}
func (c connectCodec) Name() string {
return jsonCodec
}
func (c connectCodec) Marshal(message any) ([]byte, error) {
protoMessage, ok := message.(proto.Message)
if !ok {
return nil, ErrNotProto
}
return protojson.MarshalOptions{UseProtoNames: true}.Marshal(protoMessage)
}
func (c connectCodec) Unmarshal(binary []byte, message any) error {
protoMessage, ok := message.(proto.Message)
if !ok {
return ErrNotProto
}
if len(binary) == 0 {
return errors.New("zero-length payload is not a valid JSON object")
}
// Discard unknown fields so clients and servers aren't forced to always use
// exactly the same version of the schema.
options := protojson.UnmarshalOptions{DiscardUnknown: true}
err := options.Unmarshal(binary, protoMessage)
if err != nil {
return ErrNotProto
}
return nil
}