2017-10-02 7 views
2

これは私の構造体です。ソケットメッセージを受け取ると、readJsonが呼び出され、構造体がデータで満たされ、すべて正常です。それはいくつかの関数を通過しますが、Send関数を通過すると、それは奇妙な方法でシリアル化され、最終的には数値の集まりに戻り、文字列に変換するとデータが失われます。構造体をRedigo 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は、データ構造の種類をサポートしていませんか?

これは私が得るフォーマットと私が得るはずのフォーマットです。ライン55上

//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: {}}} 

私は戻って、 "壊れた" データを取得する場所である - https://play.golang.org/p/TOzJuvewlP

答えて

2

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 
} 
関連する問題