douzai3399 2019-08-03 16:19
浏览 68

将字节数组更改为Golang中的结构

I am having some data in redis. The value is stored in form of bytes. I want to fetch the bytes and map that to a struct but I am not able to decode bytes data. This is the code I am using to persist data to redis:

    import (
    bytes "bytes"
    "encoding/gob"
    "fmt"
    "github.com/go-redis/redis"
    "time"
)

var convertor bytes.Buffer
var encoder = gob.NewEncoder(&convertor)
var decoder = gob.NewDecoder(&convertor)

func Set(field string,  value interface{}) (error){
    id := "sample-key";
    err := encoder.Encode(value)
    if err!=nil {
        fmt.Printf("error occured while marshaling data")
        return err;
    }

    valueBytes := convertor.Bytes()

    err = redisdb.HSet(id, field, valueBytes).Err();
    if err!=nil{
        fmt.Printf("error occured while setting data")
        return err;
    }
    return nil;
}

This is how I get data from redis:

result, err := redisdb.HGet(key, field).Result()
if err != nil{
    fmt.Println("error occured");
}

but I am not able to store it into struct. How can decode the bytes data to a struct?

  • 写回答

2条回答 默认 最新

  • doushang9172 2019-08-03 16:40
    关注

    Reusing the bytes.Buffer between encode operations will produce unexpected results. Every call to Encode appends data to the buffer. Calling Set multiple times will write the following data to the database: (value1), (value1, value2), (value1, value2, value3) and so on. Calling the function concurrently will create a data race.

    Fix the Set function by creating a buffer and encoder for each call to the function:

    func Set(field string, value interface{}) error {
        var buf bytes.Buffer
        var encoder = gob.NewEncoder(&buf)
    
        id := "sample-key"
        err := encoder.Encode(value)
        if err != nil {
            return err
        }
        return redisdb.HSet(id, field, buf.Bytes()).Err()
    }
    

    The Get function is the inverse of the set function:

    func Get(field string, value interface{}) error {
        id := "sample-key"
        buf, err := redisdb.HGet(id, field).Bytes()
        if err != nil {
            return err
        }
        return gob.NewDecoder(bytes.NewReader(buf)).Decode(value)
    }
    

    Call the get function with a pointer to the value:

    var d Data
    err := Get(field, &d)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式