首页 > 解决方案 > 如何使用 NewSingleHostReverseProxy() 停止在 Golang 的 ReverseProxy 中显示目标 URL?

问题描述

我正在尝试在 Golang 中使用反向代理,但我无法阻止目标 ip 在浏览器中显示,即。它只是重定向到维基百科(目标)而不是显示做反向代理。谁能告诉我做错了什么?

package main

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

    "github.com/gorilla/mux"
)

func main() {
    target := "https://www.wikipedia.org"
    remote, err := url.Parse(target)
    if err != nil {
        panic(err)
    }
    proxy := httputil.NewSingleHostReverseProxy(remote)
    r := mux.NewRouter()
    r.HandleFunc("/forward/{rest:.*}", handler(remote, proxy))
    http.ListenAndServe(":8080", r)
}

func handler(ur *url.URL, p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        r.URL.Host = ur.Host
        r.URL.Scheme = ur.Scheme
        r.Host = ur.Host
        r.URL.Path = mux.Vars(r)["rest"]
        p.ServeHTTP(w, r)
    }
}

标签: goreverse-proxy

解决方案


推荐阅读