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

从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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序