-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
unmarshalProto.go
71 lines (63 loc) · 1.36 KB
/
unmarshalProto.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
package test
import (
"encoding/json"
"fmt"
"io"
"net/http"
jsoniter "github.com/json-iterator/go"
"google.golang.org/genproto/googleapis/rpc/status"
grpcStatus "google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/reflect/protoreflect"
)
type Decoder = interface {
Decode(interface{}) error
}
func UnmarshalError(data []byte) error {
var s status.Status
err := protojson.Unmarshal(data, &s)
if err != nil {
return err
}
return grpcStatus.ErrorProto(&s)
}
func Unmarshal(code int, input io.Reader, v protoreflect.ProtoMessage) error {
var data json.RawMessage
err := json.NewDecoder(input).Decode(&data)
if err != nil {
return err
}
fmt.Printf("data: %s\n", data)
if code != http.StatusOK {
return UnmarshalError(data)
}
var item struct {
Result json.RawMessage `json:"result"`
Error json.RawMessage `json:"error"`
}
err = jsoniter.Unmarshal(data, &item)
if err != nil {
return err
}
if len(item.Result) == 0 && len(item.Error) == 0 {
u := protojson.UnmarshalOptions{
DiscardUnknown: true,
}
err := u.Unmarshal(data, v)
if err != nil {
return err
}
return nil
}
if len(item.Error) > 0 {
return UnmarshalError(item.Error)
}
u := protojson.UnmarshalOptions{
DiscardUnknown: true,
}
err = u.Unmarshal(item.Result, v)
if err != nil {
return err
}
return nil
}