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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示