-
Notifications
You must be signed in to change notification settings - Fork 0
/
codecs.go
executable file
·78 lines (66 loc) · 2.09 KB
/
codecs.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
package campid
import (
"encoding/gob"
"encoding/json"
"io"
"github.com/influx6/npkg/nerror"
"github.com/vmihailenco/msgpack/v5"
)
type Codec interface {
Encode(w io.Writer, s interface{}) error
Decode(w io.Reader, s interface{}) error
}
// MsgPackCodec implements the LoginCodec interface for using
// the MsgPack LoginCodec.
type MsgPackCodec struct{}
// Encode encodes giving session using the internal MsgPack format.
// Returning provided data.
func (gb *MsgPackCodec) Encode(w io.Writer, s interface{}) error {
if err := msgpack.NewEncoder(w).Encode(s); err != nil {
return nerror.Wrap(err, "Failed to encode giving session")
}
return nil
}
// Decode decodes giving data into provided session instance.
func (gb *MsgPackCodec) Decode(r io.Reader, s interface{}) error {
if err := msgpack.NewDecoder(r).Decode(s); err != nil {
return nerror.WrapOnly(err)
}
return nil
}
// JsonCodec implements the LoginCodec interface for using
// the Json LoginCodec.
type JsonCodec struct{}
// Encode encodes giving session using the internal Json format.
// Returning provided data.
func (gb *JsonCodec) Encode(w io.Writer, s interface{}) error {
if err := json.NewEncoder(w).Encode(s); err != nil {
return nerror.Wrap(err, "Failed to encode giving session")
}
return nil
}
// Decode decodes giving data into provided session instance.
func (gb *JsonCodec) Decode(r io.Reader, s interface{}) error {
if err := json.NewDecoder(r).Decode(s); err != nil {
return nerror.WrapOnly(err)
}
return nil
}
// GobCodec implements the LoginCodec interface for using
// the gob LoginCodec.
type GobCodec struct{}
// Encode encodes giving session using the internal gob format.
// Returning provided data.
func (gb *GobCodec) Encode(w io.Writer, s interface{}) error {
if err := gob.NewEncoder(w).Encode(s); err != nil {
return nerror.Wrap(err, "Failed to encode giving session")
}
return nil
}
// Decode decodes giving data into provided session instance.
func (gb *GobCodec) Decode(r io.Reader, s interface{}) error {
if err := gob.NewDecoder(r).Decode(s); err != nil {
return nerror.WrapOnly(err)
}
return nil
}