func main() { mh := codec.MsgpackHandle{} mh.MapType = reflect.TypeOf(map[string]interface{}(nil)) buf := make([]byte, 10240) b := B{"hello", 3} msg_b := struct{ B B }{b} fmt.Printf("Send %#v\n", msg_b) enc := codec.NewEncoderBytes(&buf, &mh) err := enc.Encode(msg_b) if err != nil { log.Fatalf("Encode: %s", err) } var rcv interface{} dec := codec.NewDecoderBytes(buf, &mh) err = dec.Decode(&rcv) if err != nil { log.Fatalf("Decode: %s", err) } fmt.Printf("Raw Recv: %#v\n", rcv) var msg MSG dec = codec.NewDecoderBytes(buf, &mh) err = dec.Decode(&msg) if err != nil { log.Fatalf("Decode: %s", err) } fmt.Printf("Msg Recv: %#v\n", msg) fmt.Printf("Msg.A Recv: %#v\n", msg.A) fmt.Printf("Msg.B Recv: %#v\n", msg.B) }
// Iterate over a key range, start inclusive, end exclusive. The value is always placed into // the 'value' interface in order to allow typing. If fun returns an error the iteration is // aborted. func (db *DB) Iterate(from, to string, value interface{}, fun func(key string) error) error { slice := &dbutil.Range{[]byte(from), []byte(to)} if len(to) == 0 { slice.Limit = append(slice.Start, 0xFF) } glog.V(4).Infof("Iterating from %s to %s", string(slice.Start), string(slice.Limit)) iter := db.ldb.NewIterator(slice, nil) defer iter.Release() for iter.Next() { glog.V(4).Infof(" Iter: %s=>%#v", string(iter.Key()), iter.Value()) d := codec.NewDecoderBytes(iter.Value(), &mh) err := d.Decode(value) if err != nil { return err } err = fun(string(iter.Key())) if err != nil { return err } } glog.V(4).Infof("Done iterating from %s to %s", string(slice.Start), string(slice.Limit)) return nil }
// Get performs a key lookup in the store and returns the value. It handles decoding // the value into the interface provided using msgPack. func (db *DB) Get(key string, value interface{}) error { glog.V(3).Infoln("get", key) data, err := db.ldb.Get([]byte(key), nil) if err == leveldb.ErrNotFound { return ErrNotFound } if err != nil { return fmt.Errorf("database.Get key %s: %s", key, err.Error()) } d := codec.NewDecoderBytes(data, &mh) err = d.Decode(value) if err != nil { return fmt.Errorf("database.Get decoding for key %s: %s", key, err.Error()) } return nil }
// Receive receives a message sent across the channel from // a sender on the other side of the transport. func (c *channel) Receive(message interface{}) error { if c.direction == outbound { return ErrWrongDirection } buf, readErr := c.stream.ReadData() if readErr != nil { if readErr == io.EOF { c.stream.Close() } return readErr } decoder := codec.NewDecoderBytes(buf, c.session.handler) decodeErr := decoder.Decode(message) if decodeErr != nil { return decodeErr } return nil }