agent: Refactor msgpack serialization into util

This commit is contained in:
Armon Dadgar 2014-08-29 11:24:41 -07:00
parent 89f258ca2e
commit 6a6885ec18
2 changed files with 17 additions and 16 deletions

View File

@ -1,12 +1,10 @@
package agent
import (
"bytes"
"fmt"
"regexp"
"github.com/hashicorp/consul/consul/structs"
"github.com/ugorji/go/codec"
)
const (
@ -79,7 +77,7 @@ func (a *Agent) UserEvent(dc string, params *UserEvent) error {
// Format message
params.ID = generateUUID()
params.Version = userEventMaxVersion
payload, err := encodeUserEvent(&params)
payload, err := encodeMsgPack(&params)
if err != nil {
return fmt.Errorf("UserEvent encoding failed: %v", err)
}
@ -114,7 +112,7 @@ func (a *Agent) handleEvents() {
case e := <-a.eventCh:
// Decode the event
msg := new(UserEvent)
if err := decodeUserEvent(e.Payload, msg); err != nil {
if err := decodeMsgPack(e.Payload, msg); err != nil {
a.logger.Printf("[ERR] agent: Failed to decode event: %v", err)
continue
}
@ -253,15 +251,3 @@ func (a *Agent) LastUserEvent() *UserEvent {
idx := (((a.eventIndex - 1) % n) + n) % n
return a.eventBuf[idx]
}
// Decode is used to decode a MsgPack encoded object
func decodeUserEvent(buf []byte, out interface{}) error {
return codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)
}
// encodeUserEvent is used to encode user event
func encodeUserEvent(msg interface{}) ([]byte, error) {
var buf bytes.Buffer
err := codec.NewEncoder(&buf, msgpackHandle).Encode(msg)
return buf.Bytes(), err
}

View File

@ -1,6 +1,7 @@
package agent
import (
"bytes"
crand "crypto/rand"
"fmt"
"math"
@ -9,6 +10,8 @@ import (
"os/exec"
"runtime"
"time"
"github.com/ugorji/go/codec"
)
const (
@ -76,3 +79,15 @@ func generateUUID() string {
buf[8:10],
buf[10:16])
}
// decodeMsgPack is used to decode a MsgPack encoded object
func decodeMsgPack(buf []byte, out interface{}) error {
return codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)
}
// encodeMsgPack is used to encode an object with msgpack
func encodeMsgPack(msg interface{}) ([]byte, error) {
var buf bytes.Buffer
err := codec.NewEncoder(&buf, msgpackHandle).Encode(msg)
return buf.Bytes(), err
}