Golang访问Gin.H的元素

huangapple go评论74阅读模式
英文:

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{
		&quot;message&quot;: &quot;{\&quot;12345\&quot;:\&quot;on\&quot;,\&quot;23456\&quot;:\&quot;off\&quot;,}&quot;,
	}
    ...

And I wish to do something with it in streamRoom()

streamRoom() @ route.go

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

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

When trying to access the element in msg, e.g.

element := msg[&quot;message&quot;].(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)[&quot;message&quot;]

huangapple
  • 本文由 发表于 2021年9月7日 15:04:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/69083732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定