doupang3062 2017-10-06 14:53
浏览 654

从golang Post Form获取动态数组

I am currently working in Golang, I am developing an API, in a POST handler I need to receive in the Post form an array but with named positions, I mean, something like this:

myarray[a]:"some Value"
myarray[otherName]: "some Other value"
myarray[x] : "something different"

Right now I am trying making the Post request using curl in the CLI. I am sending this:

curl -i -X POST --url http://localhost:20000/myendpoint -H "Content-Type: application/x-www-form-urlencoded" -d 'Name=Comp&myarray[x]=somethingdifferent&myarray[otherName]=someOtherValue'

And, indeed when I print the form values in Go, I get:

[myarray[x]:[somethingdifferent] myarray[otherName]:[someOtherValue]]

Until here I understand everything, then I need to get the array myarray in a golang variable, how can I do this? When I do:

req.Form["myarray"]

I get nothing there, my purpose is to get that array and store it as a JSON object in the database due that I don't know which field can be sent in that array. I need something like:

myarray[[x]=somethingdifferent,[otherName]=someOtherValue]
  • 写回答

1条回答 默认 最新

  • doujiu1447 2017-10-07 06:57
    关注

    You may parse it yourself:

    func extractDynArray(form url.Values, key string) (result map[string]interface{}, err error) {
        result = make(map[string]interface{})
        reg, err := regexp.Compile(`^([a-z]+)\[([a-z]+)\]$`)
        if err != nil {
            log.Fatalf("Error compiling regexp: %v", err)
        }
        var matches [][]string
        for k, v := range form {
            matches = reg.FindAllStringSubmatch(k, -1)
            if len(matches) != 1 {
                continue
            }
            if key != "" && matches[0][1] != key {
                continue
            }
            if len(matches[0]) != 3 {
                continue
            }
            result[matches[0][2]] = v
        }
        return
    }
    
    func handler(w http.ResponseWriter, r *http.Request) {
        err := r.ParseForm()
        if err != nil {
            log.Fatalf("Cannot parse form %v", err)
        }
        //form := r.Form["myarray"]
        fmt.Printf("Form: %+v
    ", r.Form)
        fmt.Printf("Form myarray: %+v 
    ", r.Form["myarray"])
        parsed, err := extractDynArray(r.Form, "myarray")
        fmt.Printf("Parsed: %v. Err: %v", parsed, err)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器