首页 > 解决方案 > Golang 访问 Gin.H 的元素

问题描述

尝试该示例以了解它是否可以是 pubsub,我想知道是否可以解析或访问 gin.H 映射中的元素。我想在 POST 中发送一个 Json。

roomPOST() @route.go

    ...
    post := gin.H{
        "message": "{\"12345\":\"on\",\"23456\":\"off\",}",
    }
    ...

我希望在 streamRoom() 中用它做点什么

streamRoom() @ route.go

    ...
    c.Stream(func(w io.Writer) bool {
        select {
        case msg := <-listener:
            ...
            fmt.Printf("msg: %s %s\n", reflect.TypeOf(msg), msg)
            ...
    }

msg: gin.H map[message:{"12345":"on","23456":"off"}]

当尝试访问 msg 中的元素时,例如

element := msg["message"].(string)

它抛出:

invalid operation: cannot index msg (variable of type interface{})

请告知我如何访问 Gin.H 的元素。

标签: gogo-gin

解决方案


I wonder if it is possible to parse or access the elements in gin.H map

gin.H is defined as type H map[string]interface{}. You can index it just like a map.

In your code, msg is an interface{} whose dynamic type is gin.H, as seen from the output of reflect.TypeOf, so you can't index it directly. Type-assert it and then index it:

content := msg.(gin.H)["message"]

推荐阅读