登录
首页 >  Golang >  Go问答

使用对象而非字节发送新请求的方法

来源:stackoverflow

时间:2024-03-22 22:18:35 131浏览 收藏

在使用 HTTP 发送数据时,需要发送对象而不是字节,以确保服务器能够正确处理数据。本文介绍了如何通过设置正确的请求头和发送 JSON 格式的数据来实现这一目标。通过将内容类型设置为 "application/json" 并将数据对象转换为字节,可以确保发送的是对象而不是字节。此外,还应检查错误并导出结构字段,以避免出现 JSON 字符串为空的情况。

问题内容

我需要发送一个数据对象,例如{你好:“world”,再见:“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()
}()

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

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


解决方案


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

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 字符串变空的原因。通过将每个字段的第一个字母大写,使结构字段可导出。

今天关于《使用对象而非字节发送新请求的方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>