gpt4 book ai didi

go - 将 Struct 传递给 redigo Send 函数会破坏它并且数据丢失

转载 作者:IT王子 更新时间:2023-10-29 01:38:31 31 4
gpt4 key购买 nike

这是我的结构,当我收到套接字消息时,我读取了 Json 并且结构中填充了数据,一切都很好。它通过一些函数,但是一旦它通过发送函数,它就会以一种奇怪的方式对其进行序列化,最终我得到一堆数字,当我将它转换为字符串时,数据丢失了。

type Reply struct {
Topic string `redis:"topic" json:"topic"`
Ref string `redis:"ref" json:"ref"`
Payload struct {
Status string `redis:"status" json:"status"`
Response map[string]interface{} `redis:"response" json:"response"`
} `json:"payload"`
}

我只想以这种格式广播消息。

这是我得到修改过的和有问题的数据的地方

func (rr *redisReceiver) run() error {
l := log.WithField("channel", Channel)
conn := rr.pool.Get()
defer conn.Close()
psc := redis.PubSubConn{Conn: conn}
psc.Subscribe(Channel)
go rr.connHandler()
for {
switch v := psc.Receive().(type) {
case redis.Message:
rr.broadcast(v.Data)
case redis.Subscription:
l.WithFields(logrus.Fields{
"kind": v.Kind,
"count": v.Count,
}).Println("Redis Subscription Received")
log.Println("Redis Subscription Received")
case error:
return errors.New("Error while subscribed to Redis channel")
default:
l.WithField("v", v).Info("Unknown Redis receive during subscription")
log.Println("Unknown Redis receive during subscription")
}
}
}

难道Redigo不支持那种数据结构吗?

这是我得到的格式和我应该得​​到的格式。

//Get
"{{spr_reply sketchpad map[] 1} {ok map[success:Joined successfully]}}"
//Supposed to get
{event: "spr_reply", topic: "sketchpad", ref: "45", payload: {status:
"ok", response: {}}}

第 55 行是我取回“损坏”数据的地方 - https://play.golang.org/p/TOzJuvewlP

最佳答案

雷戈 supports the following conversions to Redis bulk strings :

Go Type                 Conversion
[]byte Sent as is
string Sent as is
int, int64 strconv.FormatInt(v)
float64 strconv.FormatFloat(v, 'g', -1, 64)
bool true -> "1", false -> "0"
nil ""
all other types fmt.Print(v)

Reply 类型使用 fmt.Print(v) 进行编码。

您似乎想将值编码为 JSON。如果是这样,请在应用程序中进行编码。您可以删除 redis 字段标签。

writeToRedis(conn redis.Conn, data Reply) error {
p, err := json.Marshl(data)
if err != nil {
return errors.Wrap(err, "Unable to encode message to json")
}
if err := conn.Send("PUBLISH", Channel, p); err != nil {
return errors.Wrap(err, "Unable to publish message to Redis")
}
if err := conn.Flush(); err != nil {
return errors.Wrap(err, "Unable to flush published message to Redis")
}
return nil
}

关于go - 将 Struct 传递给 redigo Send 函数会破坏它并且数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46519415/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com