将 Redis 订阅 []uint8 输出转换为字符串

Convert Redis subscribe []uint8 output to string

我正在使用下面提到的代码从 Redis 发布-订阅获取输出。 Redis 发布期间传递的消息是一个字符串(test-message).

但是,我在订阅阶段得到的输出是 []uint8 类型的。以下是我 运行 下面提到的代码 [116 101 115 116 45 109 101 115 115 97 103 101] 时得到的输出(而不是预期输出的 test-message

这是由下面提到的代码中的这一行引起的 fmt.Println("Output: ", v.Data, reflect.TypeOf(v.Data)).

如何在上述行的订阅中获得我想要的正确输出(即 test-message)? 我觉得我可能需要从 []uint8string 以获得正确的输出。

我的代码如下。我用这个 作为我代码的参考。

package main

import (
    "fmt"
    "log"
    "reflect"
    "time"

    "github.com/gomodule/redigo/redis"
)

func main() {
    fmt.Println("Start redis test.")

    c, err := redis.Dial("tcp", "localhost:6379")
    if err != nil {
        log.Println(err)
    } else {
        log.Println("No error during redis.Dial.")
    }
    // defer c.Close()

    val := "test-message"

    /// Publisher.
    go func() {
        c, err := redis.Dial("tcp", "localhost:6379")
        if err != nil {
            panic(err)
        }

        count := 0
        for {
            c.Do("PUBLISH", "example", val)
            // c.Do("PUBLISH", "example",
            //  fmt.Sprintf("test message %d", count))
            count++
            time.Sleep(1 * time.Second)
        }
    }()
    /// End here

    /// Subscriber.
    psc := redis.PubSubConn{Conn: c}
    psc.Subscribe("example")

    for {
        switch v := psc.Receive().(type) {
        case redis.Message:
            //fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
            fmt.Println("Output: ", v.Data, reflect.TypeOf(v.Data))
        case redis.Subscription:
            fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
        case error:
            fmt.Println(v)
        }

        time.Sleep(1)
    }
    /// End here

}

[]uint8[]byte and a byte slice can be converted to string using a conversion expression 同义。

  1. Converting a slice of bytes to a string type yields a string whose successive bytes are the elements of the slice.
string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'})   // "hellø"
string([]byte{})                                     // ""
string([]byte(nil))                                  // ""

type MyBytes []byte string(MyBytes{'h', 'e', 'l', 'l', '\xc3',
'\xb8'})  // "hellø"

所以以下内容应该足够了:

string(v.Data)

您也可以使用 fmt 中的 %s 动词不转换地打印字符串:

fmt.Printf("Output: %s", v.Data)

示例:https://play.golang.org/p/JICYPfOt-fQ

data := []uint8(`test-message`)
fmt.Println(data)
fmt.Println(string(data))
fmt.Printf("%s\n", data)