go - 构造一个 JSON 值作为 HTTP 请求的一部分进行 POST
问题描述
我目前正在尝试构建一个变量,将其转换为 JSON 并使用它发布到我的数据库。
但是,每次我尝试发布数据时,它都会返回“JSON 无效”错误,表明它的构造不正确。
我需要传入两个变量,它们通过作为查询值传入作为请求的一部分进行初始化。
有谁知道为什么我的 JSON 无效?
这是我的代码:
dataString := string(` { "credentials_id": "12345", "user_id": "12", "variable1": ` + variable1 + `, "variable2": ` + variable2 + ` }`)
fmt.Println(dataString)
req, err = http.NewRequest("POST", "https://api-call-url/bla", strings.NewReader(finalDataString))
if err != nil {
log.Print(err)
fmt.Println("Error was not equal to nil at first stage.")
os.Exit(1)
}
req.Header.Add("apikey", os.Getenv("APIKEY"))
req.Header.Add("Authorization", "Bearer "+os.Getenv("APIKEY"))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Prefer", "return=representation")
resp, err = client.Do(req)
if err != nil {
fmt.Println("Error posting data to database.")
os.Exit(1)
}
respBody, _ = ioutil.ReadAll(resp.Body)
w.WriteHeader(resp.StatusCode)
w.Write(respBody)
解决方案
您应该如这些示例json.Marshal
中所示的有效负载数据。
所以像:
import (
"bytes"
"encoding/json"
"net/http"
)
[...]
payload, _ := json.Marshal(map[string]string{
"credentials_id": "12345",
"user_id": "12",
"variable1": variable1,
"variable2": variable2,
})
req, err = http.NewRequest("POST", "https://api-call-url/bla", bytes.NewReader(payload))
[...]
defer resp.Body.Close()
respBody, _ = ioutil.ReadAll(resp.Body)
var data interface{}
json.Unmarshal([]byte(respBody), &data)
你可以在这里找到一个完整的例子。
推荐阅读
- kotlin - LifecycleScope.launchWhenStarted CoroutineScope 在函数 lambda 中不可用吗?
- c# - 使用 aspose word 将字母转换为 PDF 时无法识别毛利人的长音符号
- google-cloud-dataflow - 尝试从 Apache Beam 中的选项获取值时出现空指针异常
- db2 - 高安全性设置:是否可以从 Windows 客户端通过代理访问 Db2 服务器?
- jquery - 如何在 Jquery 中替换数组中的多个特殊字符?
- google-analytics - 谷歌分析电子商务报告数据未显示在谷歌分析网站中?
- reactjs - 按顺序删除Array中的对象但第一个
- laravel - 我无法禁用 Laravel 调试日志记录?
- airflow - 构建可配置数据迁移工具的框架
- python - Python根据条件将值转移到列