go - 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 的元素。
解决方案
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"]
推荐阅读
- wordpress - 页面上方的空白无法删除
- php - 允许按 WooCommerce 存档页面上的特色对产品进行排序
- ios - 为 Apple Silicon mac 模拟器构建静态库
- wordpress - wordpress:你能预览页面看起来像你没有登录吗?
- r - 如何获得中值或平均值并进行二分法
- c# - MVVM 可编辑组合框,无需更改 SelectedItem
- google-app-engine - 从 App Engine 在 Google Compute Engine 中执行 python 脚本
- android - 与 Expo 反应本机应用程序。APK 安装但无法打开 - 入口点?
- ruby - GraphQL API 失去连接
- c - 在 C 中超过 1024x1024 矩阵时,总线错误/核心转储