go - 如何使用对象而不是字节发送新请求?
问题描述
我需要发送一个数据对象,例如{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()
}()
我遇到的问题是因为我们将它作为一个字节发送,服务器总是返回错误响应,因为它期望处理一个对象。
如何确保它发送的是对象而不是字节?
解决方案
您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 字符串变为空的原因。通过使每个字段的首字母大写,使您的结构字段可导出。
推荐阅读
- sql - 生成预约时间段
- elasticsearch - 如何在弹性搜索查询的帮助下使用公共字段和使用 transform 合并两个数据集
- ios - AVPlayer 无法通过 setRate:time:atHostTime: 服务同步播放请求,直到其状态为 AVPlayerStatusReadyToPlay
- python - 如何在python中将字符串'Ymd hms'转换为timestruct'Ymd'
- java - 返回包含来自rest api的项目的列表的问题
- django - 我知道 Django 和颤振。可以用这两个做网站吗?如果是,我们可以为移动应用程序使用相同的代码吗?
- r - 如何在 R 中加载远程 .Rdata 文件?
- api - 用于获取数据的 REST 批量端点
- python - 关闭 tkinter.filedialog 后无法在 pygame 中拖动窗口
- swift - 正则表达式:简化形式?