从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]
douliwang6896
douliwang6896 好的谢谢。那正是我所害怕的
接近 3 年之前 回复
duanpao4522
duanpao4522 抱歉,该问题应该是“您不能使用切片”。
接近 3 年之前 回复
douhanshu5517
douhanshu5517 似乎在这个问题上,关于数组和map/hash/dictionary之间的差异普遍存在混淆。
接近 3 年之前 回复
druybew06513
druybew06513 这里没有捷径,您需要解析这些字符串并将其分配给地图。json数组不能具有字符串索引,因此您可以使用切片(并且您不希望在Go中使用数组)。
接近 3 年之前 回复
duankui1532
duankui1532 正确,现在我将它们作为两个单独的变量获取,但是我需要以某种方式将它们存储在一个数组中,这样我才能将其转换为json并保存
接近 3 年之前 回复
dpd66100
dpd66100 这不是HTTP查询参数的工作原理,您有2个单独的变量,分别称为“myarray[x]”和“myarray[otherName]”。您是否正在尝试将其解析为地图?
接近 3 年之前 回复

1个回答

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)
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问