英文:
Golang accessing elements of Gin.H
问题
尝试使用示例来确定是否可以将其作为发布-订阅功能。我想知道是否可以解析或访问gin.H映射中的元素。我想在POST请求中发送一个JSON。
在route.go的roomPOST()函数中:
...
post := gin.H{
"message": "{\"12345\":\"on\",\"23456\":\"off\"}",
}
...
我希望在streamRoom()函数中对其进行处理:
在route.go的streamRoom()函数中:
...
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的元素。
英文:
trying out the example to find out if the it can be a pubsub, I wonder if it is possible to parse or access the elements in gin.H map. I want to send a Json in a POST.
roomPOST() @ route.go
...
post := gin.H{
"message": "{\"12345\":\"on\",\"23456\":\"off\",}",
}
...
And I wish to do something with it in 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"}]
When trying to access the element in msg, e.g.
element := msg["message"].(string)
it throws:
invalid operation: cannot index msg (variable of type interface{})
Please advise how I can access the elements of Gin.H.
答案1
得分: 1
gin.H
被定义为 type H map[string]interface{}
。你可以像操作普通的 map 一样对其进行索引。
在你的代码中,msg
是一个 interface{}
类型,其动态类型是 gin.H
,可以从 reflect.TypeOf
的输出中看到,所以你不能直接对其进行索引。你需要先进行类型断言,然后再进行索引操作:
content := msg.(gin.H)["message"]
英文:
> 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"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论