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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog