Golang访问Gin.H的元素



尝试这个例子,看看它是否可以是一个公共订阅,我想知道是否有可能解析或访问在ginh地图中的元素。我想在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 %sn", 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的元素。

我想知道是否可以解析或访问ginh map中的元素

gin.H定义为type H map[string]interface{}。你可以把它像地图一样编入索引。

在你的代码中,msg是一个动态类型为gin.Hinterface{},从reflect.TypeOf的输出可以看出,所以你不能直接索引它。类型断言,然后索引它:

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

最新更新