构建一个完整的Go语言HTTP反向代理所需的内容是什么?

huangapple go评论78阅读模式
英文:

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

问题

一个真正的反向代理完成以下任务:

  1. 负载均衡:真正的反向代理可以根据不同的负载均衡算法将请求分发到多个后端服务器上,以提高性能和可靠性。

  2. 动态配置:真正的反向代理可以根据需要动态地配置后端服务器的路由规则和负载均衡策略,以适应不同的业务需求。

  3. 缓存:真正的反向代理可以缓存静态内容或经常访问的动态内容,以减轻后端服务器的负载并提高响应速度。

  4. 安全性:真正的反向代理可以提供安全功能,如SSL终止、访问控制和DDoS防护,以保护后端服务器免受恶意攻击。

  5. 日志记录和监控:真正的反向代理可以记录请求和响应的日志,并提供监控和统计信息,以便进行故障排除和性能优化。

总之,真正的反向代理不仅仅是简单地将请求转发给后端服务器,还提供了更多的功能和灵活性,以满足复杂的应用场景和需求。

英文:

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. Some complain about direct ip access. I suspect virtual hosts don't work? not sure.

What does a true reverse proxy do that makes it complete?

答案1

得分: 3

在Go语言中实现反向HTTP代理的最简单方法是使用标准库中的httputil.ReverseProxy类型。

这使您可以灵活地设置一个Director函数,该函数可以修改传入的请求,并设置一个Transport来可能地修改请求和/或实时修改响应。

它应该能够处理绝大多数反向代理情况。我在我的一个项目中非常成功地使用了它。

英文:

The simplest way to implement a reverse HTTP proxy in Go is with the httputil.ReverseProxy type in the standard library.

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.

It should be able to handle the vast majority of reverse proxy situations. I use it with great success in a project of mine.

huangapple
  • 本文由 发表于 2017年8月18日 13:59:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/45749482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定