如何转储HTTP GET请求的响应并将其写入http.ResponseWriter?

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

How to dump a response of an HTTP GET request and write it in http.ResponseWriter

问题

我正在尝试将HTTP GET请求的响应转储并将完全相同的响应写入http.ResponseWriter。以下是我的代码:

package main

import (
	"net/http"
	"net/http/httputil"
)

func handler(w http.ResponseWriter, r *http.Request) {
	resp, _ := http.Get("http://google.com")
	dump, _ := httputil.DumpResponse(resp, true)
	w.Write(dump)
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

我得到了google.com的完整HTML代码页面,而不是Google首页。有没有办法实现类似代理的效果?

英文:

I am trying to do it to dump the response of an HTTP GET request and write the very same response in an http.ResponseWriter. Here is my code:

package main

import (
	"net/http"
	"net/http/httputil"
)

func handler(w http.ResponseWriter, r *http.Request) {
	resp, _ := http.Get("http://google.com")
	dump, _ := httputil.DumpResponse(resp,true)
	w.Write(dump)
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

I get a full page of HTML code of google.com instead of the Google front page. Is there a way I can achieve a proxy-like effect?

答案1

得分: 13

将请求的头部、状态和响应体复制到响应写入器中:

resp, err := http.Get("http://google.com")
if err != nil {
    // 处理错误
}
defer resp.Body.Close()

// 头部

for name, values := range resp.Header {
    w.Header()[name] = values
}

// 状态(必须在设置头部之后、复制响应体之前)

w.WriteHeader(resp.StatusCode)

// 响应体

io.Copy(w, resp.Body)

如果你正在创建一个代理服务器,那么 net/http/httputil ReverseProxy 类型 可能会有所帮助。

英文:

Copy the headers, status and response body to the response writer:

resp, err :=http.Get("http://google.com")
if err != nil {
    // handle error
}
defer resp.Body.Close()

// headers

for name, values := range resp.Header {
    w.Header()[name] = values
}

// status (must come after setting headers and before copying body)

w.WriteHeader(resp.StatusCode)

// body

io.Copy(w, resp.Body)

If you are creating a proxy server, then the net/http/httputil ReverseProxy type might be of help.

huangapple
  • 本文由 发表于 2016年12月24日 22:06:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/41313949.html
匿名

发表评论

匿名网友

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

确定