drwpbrv668670 2017-03-18 04:03
浏览 464
已采纳

如何从golang的查询中获取数组键的值

I have this query

site.com/?status[0]=1&status[1]=2&status[1]=3&name=John

I want to get all the values of status key like

1, 2, 3

I tried something like this

for _, status:= range r.URL.Query()["status"] {
    fmt.Println(status)
}

but it only works if the query is without array key: site.com/?status=1&status=2&status=3&name=John

  • 写回答

1条回答 默认 最新

  • dongliang2058 2017-03-18 04:48
    关注

    One approach is to loop over the possible values and append to a slice as you go:

    r.ParseForm()  // parses request body and query and stores result in r.Form
    var a []string
    for i := 0; ; i++ {
        key := fmt.Sprintf("status[%d]", i)
        values := r.Form[key] // form values are a []string
        if len(values) == 0 {
            // no more values
            break
        }
        a = append(a, values[i])
        i++
    }
    

    If you have control over the query string, then use this format:

     site.com/?status=1&status=2&status=3&name=John
    

    and get status values using:

     r.ParseForm()
     a := r.Form["status"]  // a is []string{"1", "2", "3"}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分