无法将 JSON 响应解码为结构体。

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

unable to decode json response into struct

问题

你的问题是你无法将键"result"映射到OpsGenieResponse.Result。你的代码看起来没有问题,但是你的响应体的格式可能不正确。根据你提供的响应示例,它看起来是一个无效的JSON格式。请确保你的响应体是有效的JSON,并且与你的结构体定义匹配。你可以使用jsonlint.com等在线工具验证你的JSON格式是否正确。如果你的JSON格式正确,那么问题可能出在其他地方,你可以检查一下你的网络连接和OpsGenie API的文档,看看是否有其他要求或限制。

英文:
➜ curl -H 'Authorization: GenieKey KEY' https://api.opsgenie.com/v2/heartbeats/NAME/ping

{"result":"PONG - Heartbeat received","took":0.009,"requestId":"75fb5c6a-2b74-4298-a51c-384a56bcc193"}

this is my go code

type OpsGenieResponse struct {
	Result    string  `json:"result"`
	Took      float64 `json:"took"`
	RequestID string  `json:"requestId"`
}

req, _ := http.NewRequest(
		http.MethodGet,
		"https://api.opsgenie.com/v2/heartbeats/NAME/ping", 
		nil,
	)
	req.Header.Set("Accept", "application/json")
    req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "GenieKey KEY")

    api := &http.Client{
		Timeout: time.Second * 10,
	}
    resp, err := api.Do(req)

    if err != nil {
        log.Fatal(err)
    }

	var data OpsGenieResponse
	d := json.NewDecoder(resp.Body)
	d.Decode(&data)
	fmt.Println(data)
    fmt.Println("Heartbeat is ON")

And I always get this:

{ 0.001 c40e629c-f40a-48d7-ba9e-49d15520af11}
Heartbeat is ON

so I'm unable to get the key "result" mapped to OpsGenieResponse.Result.

What am I doing wrong?

答案1

得分: 1

你应该添加一个错误结构响应并检查HTTP状态码响应,然后解码正确的响应(错误或结果)。

你的错误测试,只检查我们与HTTP服务器之间是否存在通信问题。

例如:当状态码为401时,我们有以下JSON响应,并且响应消息与OpsGenieResponse结构不匹配。

{"message":"Could not authenticate","took":0.0,"requestId":"8389eef8-aed2-477c-b27d-df688de80021"}

如何检查:

    // 检查HTTP响应状态码是否不是200
    if resp.StatusCode != http.StatusOK {
       ...
       data = myErrorStruct{}
       ...
    }
英文:

You should add an error struct response and check the HTTP status code response, than you decode the right one (error or result).

Your error test, check only if we haven't communication problems with the HTTP server.

E.g.: When status code is 401 we have this JSON response, and the response message doesn't match the OpsGenieResponse struct

{"message":"Could not authenticate","took":0.0,"requestId":"8389eef8-aed2-477c-b27d-df688de80021"}

How to check:

    // Check if the HTTP response status code is not 200
    if resp.StatusCode != http.StatusOK {
       ...
       data = myErrorStruct{}
       ...
    }

huangapple
  • 本文由 发表于 2022年4月9日 10:09:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/71804763.html
匿名

发表评论

匿名网友

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

确定