golang http forward转发实现
【摘要】 启动服务mux := http.NewServeMux()mux.HandleFunc("/", handler)srv := &http.Server{ Addr: ":2222", Handler: mux,}srv.ListenAndServe()转发http请求func handler(w http.ResponseWriter, req *http...
启动服务
mux := http.NewServeMux()
mux.HandleFunc("/", handler)
srv := &http.Server{
Addr: ":2222",
Handler: mux,
}
srv.ListenAndServe()
转发http请求
func handler(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req.Body = ioutil.NopCloser(bytes.NewReader(body))
url := fmt.Sprintf("%s://%s%s", "http", "xxx.com", req.RequestURI)
proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body))
//头信息拷贝
proxyReq.Header = make(http.Header)
for h, val := range req.Header {
proxyReq.Header[h] = val
}
//头信息修正
//proxyReq.Header.Set("Authorization", "xxx")
//proxyReq.Header.Set("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36")
//proxyReq.Header.Set("Host","xxx")
//proxyReq.Header.Set("Origin","xxx")
//proxyReq.Header.Set("Referer","xxx")
httpClient := &http.Client{}
resp, err := httpClient.Do(proxyReq)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
//拷贝返回体
for name, values := range resp.Header {
w.Header()[name] = values
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
参考:
...
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)