本文整理汇总了Golang中github.com/ugorji/go/codec.NewDecoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDecoder函数的具体用法?Golang NewDecoder怎么用?Golang NewDecoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDecoder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestMetadataSerialization
func TestMetadataSerialization(t *testing.T) {
Convey("Given a metadata structure", t, func() {
metadata := &Metadata{Name: "nom"}
marshalled := &bytes.Buffer{}
metadata.Marshal(marshalled)
marshalled = bytes.NewBuffer(marshalled.Bytes())
Convey("The marshalled form should be valid cbor", func() {
dec := codec.NewDecoder(marshalled, new(codec.CborHandle))
reheated := &Metadata{}
dec.MustDecode(reheated)
})
Convey("The marshalled form should have known keys", func() {
dec := codec.NewDecoder(marshalled, new(codec.CborHandle))
reheated := make(map[string]interface{})
err := dec.Decode(reheated)
So(err, ShouldBeNil)
v, exists := reheated["n"]
So(exists, ShouldBeTrue)
So(v, ShouldEqual, "nom")
So(marshalled.Len(), ShouldEqual, 0)
})
})
}
示例2: Stats
func (c *Client) Stats() (*ClientStats, error) {
if c.conn == nil {
return nil, nil
}
sess, err := c.Session()
if err != nil {
return nil, err
}
s, err := sess.Open()
if err != nil {
return nil, err
}
_, err = s.Write([]byte{uint8(StatsType)})
buf := []byte{0}
_, err = io.ReadFull(s, buf)
if err != nil {
return nil, err
}
switch MessageType(buf[0]) {
case StatsResultType:
dec := codec.NewDecoder(s, &msgpack)
var res ClientStats
if err := dec.Decode(&res); err != nil {
return nil, c.checkError(err)
}
return &res, nil
case ErrorType:
var msgerr Error
err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
if err != nil {
return nil, c.checkError(err)
}
return nil, errors.New(msgerr.Error)
case SuccessType:
return nil, nil
default:
return nil, c.checkError(EProtocolError)
}
}
示例3: handleConnection
func handleConnection(conn net.Conn, jobd *jobserver.JobServer, cbor *codec.CborHandle) {
defer conn.Close()
jobdv := reflect.ValueOf(jobd)
reader := bufio.NewReader(conn)
decoder := codec.NewDecoder(reader, cbor)
writer := bufio.NewWriter(conn)
encoder := codec.NewEncoder(writer, cbor)
for {
var request cborrpc.Request
err := decoder.Decode(&request)
if err == io.EOF {
return
} else if err != nil {
fmt.Printf("Error reading message: %v\n", err)
return
}
fmt.Printf("Request: %v\n", request)
response := doRequest(jobdv, request)
fmt.Printf("Response: %v\n", response)
err = encoder.Encode(response)
if err != nil {
fmt.Printf("Error encoding response: %v\n", err)
return
}
err = writer.Flush()
if err != nil {
fmt.Printf("Error writing response: %v\n", err)
return
}
}
}
示例4: loadPassiveAggressiveStateFormatV1
func loadPassiveAggressiveStateFormatV1(ctx *core.Context, r io.Reader) (core.SharedState, error) {
var header regressionMsgpack
dec := codec.NewDecoder(r, regressionMsgpackHandle)
if err := dec.Decode(&header); err != nil {
return nil, err
}
if header.Algorithm != "passive_aggressive" {
return nil, fmt.Errorf("unsupported regression algorithm: %v", header.Algorithm)
}
s := &PassiveAggressiveState{}
var d paStateMsgpack
if err := dec.Decode(&d); err != nil {
return nil, err
}
s.valueField = d.ValueField
s.featureVectorField = d.FeatureVectorField
pa, err := LoadPassiveAggressive(r)
if err != nil {
return nil, err
}
s.pa = pa
return s, nil
}
示例5: TestLatestMapEncodingNil
func TestLatestMapEncodingNil(t *testing.T) {
want := LatestMap{}
{
gobs, err := want.GobEncode()
if err != nil {
t.Fatal(err)
}
have := EmptyLatestMap
have.GobDecode(gobs)
if have.Map == nil {
t.Error("Decoded LatestMap.psMap should not be nil")
}
}
{
for _, h := range []codec.Handle{
codec.Handle(&codec.MsgpackHandle{}),
codec.Handle(&codec.JsonHandle{}),
} {
buf := &bytes.Buffer{}
encoder := codec.NewEncoder(buf, h)
want.CodecEncodeSelf(encoder)
decoder := codec.NewDecoder(buf, h)
have := EmptyLatestMap
have.CodecDecodeSelf(decoder)
if !reflect.DeepEqual(want, have) {
t.Error(test.Diff(want, have))
}
}
}
}
示例6: TestSpanMsgPack
func TestSpanMsgPack(t *testing.T) {
span := Span{Id: TestId("33f25a1a750a471db5bafa59309d7d6f"),
SpanData: SpanData{
Begin: 1234,
End: 5678,
Description: "getFileDescriptors",
Parents: []SpanId{},
TracerId: "testTracerId",
}}
mh := new(codec.MsgpackHandle)
mh.WriteExt = true
w := bytes.NewBuffer(make([]byte, 0, 2048))
enc := codec.NewEncoder(w, mh)
err := enc.Encode(span)
if err != nil {
t.Fatal("Error encoding span as msgpack: " + err.Error())
}
buf := w.Bytes()
fmt.Printf("span: %s\n", hex.EncodeToString(buf))
mh = new(codec.MsgpackHandle)
mh.WriteExt = true
dec := codec.NewDecoder(bytes.NewReader(buf), mh)
var span2 Span
err = dec.Decode(&span2)
if err != nil {
t.Fatal("Failed to reverse msgpack encoding for " + span.String())
}
ExpectSpansEqual(t, &span, &span2)
}
示例7: TestEdgeMetadatasEncodingNil
func TestEdgeMetadatasEncodingNil(t *testing.T) {
want := EdgeMetadatas{}
{
gobs, err := want.GobEncode()
if err != nil {
t.Fatal(err)
}
have := EmptyEdgeMetadatas
have.GobDecode(gobs)
if have.psMap == nil {
t.Error("needed to get back a non-nil psMap for EdgeMetadata")
}
}
{
for _, h := range []codec.Handle{
codec.Handle(&codec.MsgpackHandle{}),
codec.Handle(&codec.JsonHandle{}),
} {
buf := &bytes.Buffer{}
encoder := codec.NewEncoder(buf, h)
want.CodecEncodeSelf(encoder)
decoder := codec.NewDecoder(buf, h)
have := EmptyEdgeMetadatas
have.CodecDecodeSelf(decoder)
if !reflect.DeepEqual(want, have) {
t.Error(test.Diff(want, have))
}
}
}
}
示例8: TestCodec
// This test determines the behavior of codec with respect to advancing the
// Reader when decoding error scenarios. It seems that the codec advances
// the Reader if Decode fails, but sets its own state to expect a specific
// type for the next Decode, and thus is functionally the same as not
// advancing the Reader.
func TestCodec(t *testing.T) {
var buf bytes.Buffer
mh := &codec.MsgpackHandle{WriteExt: true}
enc := codec.NewEncoder(&buf, mh)
dec := codec.NewDecoder(&buf, mh)
var i int = math.MaxInt32
err := enc.Encode(i)
require.Nil(t, err, "expected encoding to succeed")
require.Equal(t, 5, len(buf.Bytes()), "expected buffer to contain bytes")
var targetInt int
err = dec.Decode(&targetInt)
require.Nil(t, err, "expected decoding to succeed")
require.Equal(t, math.MaxInt32, targetInt, "expected codec to successfully decode int")
require.Equal(t, 0, len(buf.Bytes()), "expected buffer to be empty")
var targetString string
enc.Encode(i)
require.Equal(t, 5, len(buf.Bytes()), "expected buffer to contain bytes")
err = dec.Decode(&targetString)
require.Error(t, err, "expected error while decoding")
require.Contains(t, err.Error(), "Unrecognized descriptor byte", "expected error while decoding")
require.Equal(t, 4, len(buf.Bytes()), "expected buffer to have bytes")
err = dec.Decode(&targetString)
require.Error(t, err, "expected error while decoding")
require.Contains(t, err.Error(), "Unrecognized descriptor byte", "expected error while decoding")
require.Equal(t, 4, len(buf.Bytes()), "expected buffer to have bytes")
targetInt = 0
err = dec.Decode(&targetInt)
require.Nil(t, err, "expected decoding to succeed")
require.Equal(t, math.MaxInt32, targetInt, "expected codec to successfully decode int")
require.Equal(t, 0, len(buf.Bytes()), "expected buffer to be empty")
}
示例9: Decode
// Decode tries to decode a restdata object from a reader, such as an
// HTTP request or response. out must be a pointer type.
func Decode(contentType string, r io.Reader, out interface{}) error {
if contentType == "" {
// RFC 7231 section 3.1.1.5
// We could also consider http.DetectContentType()
contentType = "application/octet-stream"
}
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return err
}
// Promote to more specific types
switch mediaType {
case "text/json", "application/json", JSONMediaType, V1JSONMediaType:
mediaType = V1JSONMediaType
default:
return ErrUnsupportedMediaType{Type: mediaType}
}
// Actually decode the object based on the selected type.
switch mediaType {
case V1JSONMediaType:
// (We will be happy we picked this library if we do
// CBOR over the wire; it is also used for the
// CBOR-RPC Python compatibility interface)
json := &codec.JsonHandle{}
decoder := codec.NewDecoder(r, json)
err = decoder.Decode(out)
default:
err = ErrUnsupportedMediaType{Type: mediaType}
}
return err
}
示例10: readFrames
func (c *duplexconn) readFrames() {
reader := bufio.NewReader(c.conn)
decoder := codec.NewDecoder(reader, &mh)
for {
var frame Frame
err := decoder.Decode(&frame)
if err != nil {
debug(err)
close(c.writeCh)
c.peer.Drop(c.uuid)
return
}
debug("Reading frame:", frame)
c.Lock()
ch, exists := c.channels[frame.Channel]
c.Unlock()
if exists && frame.Type == DataFrame {
if ch.HandleIncoming(&frame) {
continue
}
}
if !exists && frame.Type == OpenFrame {
if c.peer.HandleOpen(c, &frame) {
continue
}
}
debug("Dropped frame:", frame)
}
}
示例11: getConn
// getConn is used to get a connection from the pool
func (n *NetworkTransport) getConn(target net.Addr) (*netConn, error) {
// Check for a pooled conn
if conn := n.getPooledConn(target); conn != nil {
return conn, nil
}
// Dial a new connection
conn, err := n.stream.Dial(target.String(), n.timeout)
if err != nil {
return nil, err
}
// Wrap the conn
netConn := &netConn{
target: target,
conn: conn,
r: bufio.NewReader(conn),
w: bufio.NewWriter(conn),
}
// Setup encoder/decoders
netConn.dec = codec.NewDecoder(netConn.r, &codec.MsgpackHandle{})
netConn.enc = codec.NewEncoder(netConn.w, &codec.MsgpackHandle{})
// Done
return netConn, nil
}
示例12: TestHTTPPollMailboxMsgPack
func TestHTTPPollMailboxMsgPack(t *testing.T) {
reg := NewMemRegistry()
serv := NewHTTPService(cPort, reg)
reg.Declare("a")
msg := Msg("hello")
reg.Push("a", msg)
url := fmt.Sprintf("http://%s/mailbox/a", cPort)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
req.Header.Add("Accept", ctMsgPack)
rw := httptest.NewRecorder()
serv.mux.ServeHTTP(rw, req)
assert.Equal(t, 200, rw.Code, "server error")
var ret Message
err = codec.NewDecoder(rw.Body, &msgpack).Decode(&ret)
if err != nil {
panic(err)
}
assert.True(t, msg.Equal(&ret), "poll did not return a message")
}
示例13: ReadMessage
func ReadMessage(conn net.Conn, timeout time.Duration) (*Message, error) {
conn.SetReadDeadline(time.Now().Add(DefaultHeartbeatTimeout))
var lengthBuf [2]byte
_, err := conn.Read(lengthBuf[:])
if err != nil {
return nil, err
}
length := int(binary.BigEndian.Uint16(lengthBuf[:]))
if length > DefaultMessageLengthCap {
return nil, errors.New("message is too long")
}
buf := bytes.NewBuffer(make([]byte, 0, length))
_, err = io.CopyN(buf, conn, int64(length))
if err != nil {
return nil, err
}
var handle = &codec.MsgpackHandle{}
var decoder = codec.NewDecoder(buf, handle)
var result = &Message{}
err = decoder.Decode(result)
if err != nil {
return nil, err
}
return result, nil
}
示例14: loadAROWStateFormatV1
func loadAROWStateFormatV1(ctx *core.Context, r io.Reader) (core.SharedState, error) {
var header classifierMsgpack
dec := codec.NewDecoder(r, classifierMsgpackHandle)
if err := dec.Decode(&header); err != nil {
return nil, err
}
if header.Algorithm != "arow" {
return nil, fmt.Errorf("unsupported classification algorithm: %v", header.Algorithm)
}
// This is the current format and no data type conversion is required.
s := &AROWState{}
var d arowStateMsgpack
if err := dec.Decode(&d); err != nil {
return nil, err
}
s.labelField = d.LabelField
s.featureVectorField = d.FeatureVectorField
arow, err := LoadAROW(r)
if err != nil {
return nil, err
}
s.arow = arow
return s, nil
}
示例15: Decode
func (r *Request) Decode(t interface{}) {
buf := bytes.NewBuffer(r.params)
dec := codec.NewDecoder(buf, &mh)
dec.Decode(t)
return
}