英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论