Golang中如何获取完整的响应体
Golang中如何获取完整的响应体 我想获取完整的响应体,但目前只能获取到状态信息。
jumbo_rod_url :="some url "
body := strings.NewReader(string(ctx.Request.Body()))
fmt.Println("printing body",body)
req, err := http.NewRequest("POST", jumbo_rod_url,body)
req.Header.Add("Authorization", "Bearer "+jumbo_token[2])
req.Header.Add("Content-Type", "application/json")
if err != nil {
log.Panic(err)
}
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
fmt.Fprintf(ctx,"%s",resp)
fmt.Printf("%s","final response ",resp)
// 当前获取的响应
// {200 OK %!s(int=200) HTTP/1.1 %!s(int=1) %!s(int=1) map[X-Content-//Type-Options:[nosniff] X-Xss-Protection:[1;mode=block]
fmt.Println("check",resp.Body)
// 期望在Swagger中获取的响应 /// { “scope”: “/client”, “id”: { “member_id”: “” }, “access_token”: “”, “token_type”: “bearer”, “expires_in”: 3600, “refresh_token”: “”, “refresh_expires_in”: 3600 }
}
更多关于Golang中如何获取完整的响应体的实战教程也可以访问 https://www.itying.com/category-94-b0.html
7 回复
“resp” 不是字符串。请查看 https://golang.org/pkg/net/http/ 中的示例。
你好 Jakob, 我该如何获取完整的响应体而不仅仅是状态信息?
你看了 @calmh 在他帖子中链接的示例吗?
就在那里,就在第二个示例中。
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.New("Read err")
}
fmt.Printf("%s","final response ",string(respBody))
这对于字符串处理是可行的 现在你需要使用json.Unmarshal将数据解析到所需的结构体中
要获取完整的响应体,需要使用io.ReadAll()读取响应体的内容。在你的代码中,你直接打印了resp对象和resp.Body,这只会显示响应结构信息,而不是实际的响应内容。
以下是修正后的代码:
jumbo_rod_url := "some url"
body := strings.NewReader(string(ctx.Request.Body()))
fmt.Println("printing body", body)
req, err := http.NewRequest("POST", jumbo_rod_url, body)
req.Header.Add("Authorization", "Bearer "+jumbo_token[2])
req.Header.Add("Content-Type", "application/json")
if err != nil {
log.Panic(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Panic(err)
}
defer resp.Body.Close()
// 读取完整的响应体
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
log.Panic(err)
}
// 打印响应体内容
fmt.Println("完整响应体:", string(responseBody))
// 如果需要将响应写入ctx
fmt.Fprintf(ctx, "%s", string(responseBody))
关键修改:
- 使用
io.ReadAll(resp.Body)读取响应体的所有内容 - 将字节数据转换为字符串进行显示
- 添加了错误处理
这样就能获取到类似你期望的JSON格式的完整响应体:
{
"scope": "/client",
"id": {
"member_id": ""
},
"access_token": "",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "",
"refresh_expires_in": 3600
}
注意:需要导入io包:
import (
"io"
// 其他导入...
)


