我编写了一个简单的 Fetch Go 函数,它调用 API 并生成响应。
调用时,它成功地将数据记录到从 API 中提取的控制台。
我想做的是获取通过读取响应正文生成的最终“respBody”变量,然后将其返回给我的前端客户端 - 但我不知道如何。
所有示例都只使用 Println,我搜索了文档但找不到任何内容。
谁能告诉我如何更改我的代码以便我可以将 respBody 返回给客户端?
这是我的功能:
func Fetch(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request to server")
os.Exit(1)
}
respBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(respBody)) // This is the final bit where I want to send this back to the client.
}
答案 0 :(得分:1)
您可以简单地将响应正文的内容复制到响应编写器:
io.Copy(w,resp.Body)
由于您只能读取一次正文,因此上述解决方案将不允许您获取正文。如果您还想记录它或以某种方式处理它,您可以读取它,然后将其写入响应编写器。
respBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(respBody))
w.Write(respBody)
答案 1 :(得分:1)
你的函数是一个 HandlerFunc
,它包含 ResponseWriter
接口,在你的例子中它是 w
。
因此,您可以使用 http.ResponseWriter
写入数据:
func Fetch(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request to server")
os.Exit(1)
}
respBody, _ := ioutil.ReadAll(resp.Body)
// Here:
w.WriteHeader(resp.StatusCode)
w.Write(respBody)
}
您可以使用 io.Copy(w, resp.Body)
代替,记得使用 defer resp.Body.Close()
关闭正文。