reverse proxy does not work

扶醉桌前 提交于 2019-12-23 01:28:12

问题


I am using GO's reverse proxy like this, but this does not work well

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

when I visit the http://localhost:9000, I am seeing not expected page


回答1:


From this article 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.

You need to define a custom middleware to set the required host parameter:

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


来源:https://stackoverflow.com/questions/38016477/reverse-proxy-does-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!