我正在用Golang編寫一個簡單的反向代理。代碼如下所示:Golang反向代理到應用程序後面的nginx
func NewMultiHostProxy(target_urls []string) gin.HandlerFunc {
var urls []*url.URL
for i := 0; i < len(target_urls); i++ {
target, err := url.Parse(target_urls[i])
if err != nil {
fmt.Errorf("Error parsing url")
return nil
}
urls = append(urls, target)
}
return func(c *gin.Context) {
director := func(req *http.Request) {
target := urls[rand.Int()%len(urls)]
r := c.Request
req = r
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = target.Path
req.Header.Set("X-GoProxy", "GoProxy")
if target.RawQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = target.RawQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = target.RawQuery + "&" + req.URL.RawQuery
}
log.Print(req.URL)
}
proxy := &httputil.ReverseProxy{Director: director}
proxy.ServeHTTP(c.Writer, c.Request)
}
}
當我想代理一個請求Nginx的背後一個REST API,Nginx的總是返回404。不過,如果我直接訪問REST API,它正確返回結果。這裏是我的Nginx配置:
server {
listen 80;
server_name myservername;
location /api {
proxy_pass http://127.0.0.1:5000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
我可以知道如何調試此問題嗎?它是由Nginx配置引起的嗎?
嗨@cshu,感謝您的及時回覆。我已刪除重新分配的代碼,但404錯誤仍然存在。在Nginx日誌中,有一條訪問記錄,所以代理請求可以到達目標,但是,nginx日誌顯示404。 –