简体   繁体   English

在go中构建完整的HTTP反向代理需要什么?

[英]What's required to build a complete HTTP reverse proxy in go?

A naive reverse proxy is like this: 一个天真的反向代理是这样的:

package main

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

func main() { 
    // New functionality written in Go
    http.HandleFunc("/new", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "New function")
    })

    // Anything we don't do in Go, we pass to the old platform
    u, _ := url.Parse("http://www.google.com/")
    http.Handle("/", httputil.NewSingleHostReverseProxy(u))

    // Start the server
    http.ListenAndServe(":8080", nil)
}

But, this is incomplete. 但是,这是不完整的。 Depending on the website you might not get anything useful back. 根据网站的不同,您可能无法获得任何有用的信息。 Some do https redirect. 有些人做https重定向。 Some complain about direct ip access. 有些人抱怨直接ip访问。 I suspect virtual hosts don't work? 我怀疑虚拟主机不起作用? not sure. 不确定。

What does a true reverse proxy do that makes it complete? 真正的反向代理会做什么使它完整?

The simplest way to implement a reverse HTTP proxy in Go is with the httputil.ReverseProxy type in the standard library. 在Go中实现反向HTTP代理的最简单方法是使用标准库中的httputil.ReverseProxy类型。

This gives you the flexibility to set a Director function which can modify the incoming requests, and a Transport to possibly modify requests and/or responses on-the-fly. 这使您可以灵活地设置一个Director功能,可以修改传入的请求,并且Transport到可能修改即时请求和/或响应。

It should be able to handle the vast majority of reverse proxy situations. 它应该能够处理绝大多数反向代理情况。 I use it with great success in a project of mine. 我在我的一个项目中非常成功地使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM