gpt4 book ai didi

go - 反向代理不起作用

转载 作者:IT王子 更新时间:2023-10-29 01:58:46 27 4
gpt4 key购买 nike

我正在像这样使用 GO 的反向代理,但效果不佳

主要包

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

func main() {
u, _ := url.Parse("http://www.darul.io")

http.ListenAndServe(":9000", httputil.NewSingleHostReverseProxy(u))
}

当我访问 http://localhost:9000 ,我看到的不是预期的页面

enter image description here

最佳答案

来自这篇文章A Proper API Proxy Written in Go :

httputil.NewSingleHostReverseProxy does not set the host of the request to the host of the destination server. If you’re proxying from foo.com to bar.com, requests will arrive at bar.com with the host of foo.com. Many webservers are configured to not serve pages if a request doesn’t appear from the same host.

您需要定义一个自定义中间件来设置所需的主机参数:

package main

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

func sameHost(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Host = r.URL.Host
handler.ServeHTTP(w, r)
})
}

func main() {
// initialize our reverse proxy
u, _ := url.Parse("http://www.darul.io")
reverseProxy := httputil.NewSingleHostReverseProxy(u)
// wrap that proxy with our sameHost function
singleHosted := sameHost(reverseProxy)
http.ListenAndServe(":5000", singleHosted)
}

关于go - 反向代理不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38016477/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com