从转到 HTTP 请求将数据返回到客户端

我编写了一个简单的 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.


}


烙印99
浏览 94回答 2
2回答

aluckdog

您的函数是一个处理程序Func,其中包含接口,在您的情况下它是 。ResponseWriterw因此,您可以使用 :http.ResponseWriterfunc 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()

慕少森

您只需将响应正文的内容复制到响应编写器:io.Copy(w,resp.Body)由于您只能读取一次身体,因此上面的解决方案将不允许您获得身体。如果您还想记录它,或者以某种方式处理它,则可以读取它,然后将其写入响应编写器。respBody, _ := ioutil.ReadAll(resp.Body)fmt.Println(string(respBody)) w.Write(respBody)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go