反向代理不起作用

时间:2016-06-24 15:02:52

标签: go reverse-proxy

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

package main

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

1 个答案:

答案 0 :(得分:3)

从这篇文章A Proper API Proxy Written in Go

  

httputil.NewSingleHostReverseProxy不会将请求的主机设置为目标服务器的主机。如果您从foo.com代理到bar.com,请求将通过foo.com主机到达bar.com。如果请求未出现在同一主机上,则许多Web服务器配置为不提供页面。

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

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)
}