构建一个JSON值,作为HTTP请求的一部分进行POST。

huangapple go评论80阅读模式
英文:

Constructing a JSON value to POST as part of HTTP request

问题

我目前正在尝试构建一个变量,将其转换为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)

请注意,我只会返回翻译好的部分,不会回答关于翻译的问题。

英文:

I'm currently attempting to build a variable, convert it to JSON and use it to post to my database.

However, every time I try to post the data it's returning a 'JSON is not valid' error, indicating it's not constructed right.

I need to pass in two variables, which are initialised as part of the request by being passed in as query values.

Does anyone know why my JSON isn't valid?

Here's my code:

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)

答案1

得分: 3

你应该像这些示例中所示,使用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)

你可以在这里找到一个完整的示例。

英文:

You should json.Marshal the payload data as shown in these examples.

So something like:

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)

You can find a complete example here.

huangapple
  • 本文由 发表于 2021年10月5日 20:36:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/69450594.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定