从Go的HTTP请求中将数据返回给客户端

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

Returning data back to client from Go HTTP request

问题

我写了一个简单的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)) // 这是我想要将其发送回客户端的最后一部分。
}

请注意,我只翻译了代码部分,其他内容不做翻译。

英文:

I've written a simple Fetch Go function which calls an API, and generates a response.

When called, it successfully logs the data to the console which is pulled from the API.

What I want to do though is take the final 'respBody' variable generated from reading the response body, and then return it back to my frontend client - but I can't figure out how.

All the examples just use Println, and I've searched the docs but can't find anything.

Can anyone tell me how to change my code so I can return the respBody back to the client?

Here's my function:

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.

}

答案1

得分: 1

你可以简单地将响应体的内容复制到响应写入器中:

io.Copy(w, resp.Body)

由于你只能读取一次响应体,上述解决方案将不允许你获取响应体。如果你还想记录它或以某种方式处理它,你可以先读取它,然后将其写入响应写入器中。

respBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(respBody))
w.Write(respBody)
英文:

You can simply copy the contents of the response body to the response writer:

io.Copy(w,resp.Body)

Since you can only read the body once, the solution above will not allow you to get the body. If you also want to log it, or process it somehow, you can read it and then write it to the response writer.

respBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(respBody)) 
w.Write(respBody)

答案2

得分: 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)
    

    // 在这里:
    w.WriteHeader(resp.StatusCode)
    w.Write(respBody)
}

你可以使用 io.Copy(w, resp.Body) 来代替,记得使用 defer resp.Body.Close() 来关闭 body。

英文:

Your function is a HandlerFunc, which contains the ResponseWriter interface, in your case it's w.


So, you can write data using 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)
}

You can use use io.Copy(w, resp.Body) instead, remember to close body using defer resp.Body.Close().

huangapple
  • 本文由 发表于 2021年5月24日 21:36:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/67673032.html
匿名

发表评论

匿名网友

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

确定