这是我的结构,当我得到一个套接字消息时,我readJson并且结构填充了数据,一切都很好。它经历了一些函数,但是一旦它通过Send函数,它以一种奇怪的方式序列化它,最终我得到了一堆数字,当我将它转换为字符串时,数据丢失了。
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
答案 0 :(得分:3)
Redigo 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
}