↑↓ 选择 · ↵ 打开 · 共索引 377 篇

    [译]用一行 Go 代码实现一个反向代理

    用一行 Go 代码实现一个反向代理

    ARCHIVE 这篇写于 2018 年,距今 8 年多了。里面的版本、链接和做法可能都已经过时,看的时候留个心眼。

    这是一篇翻译文章。

    原文:Writing a Reverse Proxy in just one line with Go


    这是您实际需要的所有代码……

    注意 http-server 是需要你单独 npm install的。

    npm install http-server -g
    

    最核心的代码是:

    // Serve a reverse proxy for a given url
    func serveReverseProxy(target string, res http.ResponseWriter, req *http.Request) {
    	// parse the url
    	url, _ := url.Parse(target)
    
    	// create the reverse proxy
    	proxy := httputil.NewSingleHostReverseProxy(url)
    
    	// Update the headers to allow for SSL redirection
    	req.URL.Host = url.Host
    	req.URL.Scheme = url.Scheme
    	req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
    	req.Host = url.Host
    
    	// Note that ServeHttp is non blocking and uses a go routine under the hood
    	proxy.ServeHTTP(res, req)
    }
    

    茶歇驿站

    一个可以让你停下来看一看,在茶歇之余给你帮助的小站,这里的内容主要是后端技术,个人管理,团队管理,以及其他个人杂想。