首页 > 解决方案 > 如何使用对象而不是字节发送新请求?

问题描述

我需要发送一个数据对象,例如{hello: "world", goodbye: "world"}发送到 API。我现在正在这样做:

inputs := form.GetElementsByTagName("input")

var data = make(map[string]interface{}) // after adding values this looks like this: {hello: "world", goodbye: "world"}

for value := range inputs {
    // Append all values from the inputs to a new array, with the key named by the input name attribute
    if inputs[value] != nil && inputs[value].(*dom.HTMLInputElement).Value != "" {
        data[inputs[value].(*dom.HTMLInputElement).Name] = inputs[value].(*dom.HTMLInputElement).Value
    }
}

parsedData, _ := json.Marshal(data)
req, _ := http.NewRequest(method, url, bytes.NewBuffer(parsedData))

req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

client := &http.Client{}
go func() { // Must be a goroutine
    response, _ := client.Do(req)
    defer response.Body.Close()
}()

我遇到的问题是因为我们将它作为一个字节发送,服务器总是返回错误响应,因为它期望处理一个对象。

如何确保它发送的是对象而不是字节?

标签: go

解决方案


application/x-www-form-urlencoded在以 json 格式发送数据时将内容类型设置为,因此在设置请求标头时更改内容类型,同时不要跳过错误以检查返回的错误是什么:

parsedData, err := json.Marshal(data)
if err != nil{
    fmt.Println(err)
}
req, err := http.NewRequest(method, url, parsedData) // send the parseData which are bytes returned from the marshal.
if err != nil{
    fmt.Println(err)
}
req.Header.Set("Content-Type", "application/json") // set the content type to json

go func() { // Must be a goroutine
    response, err := client.Do(req)
    if err != nil{
        fmt.Println(err)
    }
    defer response.Body.Close()
}()

// you should check for response status to verify the details as
fmt.Println("response Status:", response.Status)
fmt.Println("response Headers:", response.Header)
body, _ := ioutil.ReadAll(response.Body)
fmt.Println("response Body:", string(body))

应该考虑的一件事是您尚未导出结构字段。这可能是您的 json 字符串变为空的原因。通过使每个字段的首字母大写,使您的结构字段可导出。


推荐阅读