将布尔值作为HTTP请求的响应接收

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

Receiving bool values as a response to http request

问题

我有两个服务通过HTTP请求和响应进行通信。Repo-1中的一个特定端点返回一个布尔值作为其响应。

response := checkIfPresent(personId)
return c.JSON(http.StatusOK, response)

这里的response是一个布尔值。在客户端,我这样接收响应。

client := &http.Client{}
responseBody, err := client.Do(request)
if err != nil {
    return false
}

defer responseBody.Body.Close()

response, _ := ioutil.ReadAll(responseBody.Body)

return response

然而,这里的response[]byte类型。我该如何从中获取布尔值并返回它?

英文:

I have two services communicating with each other using http requests and responses. One specific endpoint in Repo-1 returns a bool value as it's response.

response := checkIfPresent(personId)
return c.JSON(http.StatusOK, response)

Here response is a bool value. And on the client side, I am receiving the response like this.

client := &http.Client{}
responseBody, err := client.Do(request)
if err != nil {
		return false
	}
	
defer responseBody.Body.Close()

response, _ := ioutil.ReadAll(responseBody.Body)

return response 

However, here response is of the type []byte. How do I get the bool value from this and return it?

答案1

得分: 1

response是一个以字节切片形式编码的JSON数据,其中包含字符串true。你需要从JSON中解组它。

var resp bool
err := json.Unmarshal(response, &resp)
if err != nil {
  // 进行错误处理,例如:
  return false, err
}
return resp, nil

或者你可以简单地检查它是否等于字符串true

return string(response) == "true"

但是,如果以后响应将包含更多数据,只有解组的方式才是有效的。

英文:

The response is a JSON encoded data in a byte slice, containing the string true. You have to unmarshal it from the JSON.

var resp bool
err := json.Unmarshal(response, &resp)
if err != nil {
  //Do the error handling, and return, for example:
  return false, err
}
return resp, nil

Or simply you can check if its equal to the string "true" with

return string(response) == "true"

But later if the response will contain more data, only the unmarshal way will be valid.

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

发表评论

匿名网友

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

确定