frostfs-sdk-go/api/util/proto/encoding/json.go
Pavel Pogodaev 6ce73790ea
All checks were successful
DCO / DCO (pull_request) Successful in 38s
Tests and linters / Tests (pull_request) Successful in 1m13s
Tests and linters / Lint (pull_request) Successful in 2m36s
[#276] Merge repo with frostfs-api-go
Signed-off-by: Pavel Pogodaev <p.pogodaev@yadro.com>
2024-10-22 14:05:12 +00:00

48 lines
1.2 KiB
Go

package encoding
import (
"encoding/json"
"fmt"
"google.golang.org/grpc/encoding"
"google.golang.org/protobuf/encoding/protojson"
)
// JSONCodec is easyjson codec used for code generated by protogen.
// It is binary-level compatible with the standard protojson format, thus uses the same name.
type JSONCodec struct{}
var _ encoding.Codec = JSONCodec{}
func init() {
encoding.RegisterCodec(JSONCodec{})
}
// Name implements the encoding.Codec interface.
func (JSONCodec) Name() string { return "json" }
// Marshal implements the encoding.Codec interface.
func (JSONCodec) Marshal(v any) ([]byte, error) {
switch v := v.(type) {
case json.Marshaler:
return json.Marshal(v)
default:
if v := messageV2Of(v); v != nil {
return protojson.Marshal(v)
}
return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
}
}
// Unmarshal implements the encoding.Codec interface.
func (JSONCodec) Unmarshal(data []byte, v any) error {
switch v := v.(type) {
case json.Unmarshaler:
return json.Unmarshal(data, v)
default:
if v := messageV2Of(v); v != nil {
return protojson.Unmarshal(data, v)
}
return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v)
}
}