forked from mosuka/cete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshaler.go
64 lines (53 loc) · 1.26 KB
/
marshaler.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
package marshaler
import (
"encoding/json"
"io"
"io/ioutil"
"github.com/animeshon/cete/protobuf"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
var (
DefaultContentType = "application/json"
)
type CeteMarshaler struct{}
func (*CeteMarshaler) ContentType(v interface{}) string {
return DefaultContentType
}
func (j *CeteMarshaler) Marshal(v interface{}) ([]byte, error) {
switch v.(type) {
case *protobuf.GetResponse:
value := v.(*protobuf.GetResponse).Value
return value, nil
case *protobuf.MetricsResponse:
value := v.(*protobuf.MetricsResponse).Metrics
return value, nil
default:
return json.Marshal(v)
}
}
func (j *CeteMarshaler) Unmarshal(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}
func (j *CeteMarshaler) NewDecoder(r io.Reader) runtime.Decoder {
return runtime.DecoderFunc(
func(v interface{}) error {
buffer, err := ioutil.ReadAll(r)
if err != nil {
return err
}
switch v.(type) {
case *protobuf.SetRequest:
v.(*protobuf.SetRequest).Value = buffer
return nil
default:
return json.Unmarshal(buffer, v)
}
},
)
}
func (j *CeteMarshaler) NewEncoder(w io.Writer) runtime.Encoder {
return json.NewEncoder(w)
}
func (j *CeteMarshaler) Delimiter() []byte {
return []byte("\n")
}