duanla3319 2019-03-29 12:05
浏览 245
已采纳

解析msgpack编码的单个切片的msgpack编码的切片时为空片

I am trying to decode a gzip response from server which an msgpack array or msgpack array which is finally gzipped.

so to illustrate this my response looks something like:

gzip(msgpack([msgpack([]), msgpack([]), msgpack([]) ....]))

this is what I have done so far, but I am getting msgpack error

msgpack: invalid code=3f decoding array length and hence all I get is empty slices.

this getBytes function I have taken from this SO answer

func getBytes(key interface{}) ([]byte, error) {
    var buf bytes.Buffer
    enc := gob.NewEncoder(&buf)
    err := enc.Encode(key)
    if err != nil {
        return nil, err
    }
    return buf.Bytes(), nil
}

var unZipped io.Reader
unZipped, err = gzip.NewReader(resp.Body)
var dataBytes bytes.Buffer
_, err = dataBytes.ReadFrom(unZipped)
if err != nil {
    logger.Println("error un gzipping", err)
}
var packedSlices []interface{}
bytesSlice := dataBytes.Bytes()
err = msgpack.Unmarshal(bytesSlice, &packedSlices)
for _, c := range packedSlices {
    var packedSlice []interface{}
    byts, _ := getBytes(c)
    err = msgpack.Unmarshal(byts, &packedSlice)
    logger.Println(err, packedSlice)
}

When I do the same thing in python 3.7 it is working fine:

resp = requests.post(url, headers=headers, json=payload, stream=True)
datas = msgpack.loads(gzip.decompress(resp.raw.data))
datas = [msgpack.loads(k) for k in datas]

Is there something I am missing here ??

  • 写回答

1条回答 默认 最新

  • douzhang2092 2019-03-29 17:35
    关注

    Instead of using []interface{} type as unpacked type use [][]byte. Unmarshal root msg to [][]byte then iterate over slice of slices of bytes and unmarshal every child byte slice. You do not need getBytes func.

    Here some example:

    var root [][]byte
    if err :=  msgpack.Unmarshal(bytesSlice, &root); err != nil {
        panic(err)
    }
    
    for _, childBytes := range root {
        var child []interface{}
        if err := msgpack.Unmarshal(childBytes, &child); err != nil {
            panic(err)
        }
    
        _ = child
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法
  • ¥15 dnat基础问题,本机发出,别人返回的包,不能命中