# GoProxy  [](https://pkg.go.dev/github.com/elazarl/goproxy) [](https://goreportcard.com/report/github.com/elazarl/goproxy) [](https://opensource.org/licenses/BSD-3-Clause) [](https://makeapullrequest.com) [](https://github.com/avelino/awesome-go?tab=readme-ov-file#networking) GoProxy 是一个使用 Go(又称 Golang)编写的库,用于创建`定制的` HTTP/HTTPS`代理服务器`,并提供多种可配置设置。 该项目的目标是提供一个`优化过的`代理服务器,能够在合理流量下使用,同时又`可定制`且`可编程`。 代理本身就是一个 `net/http` 处理器,因此您可以在它之上添加多个中间件(panic 恢复、日志记录、压缩等)。它可以轻松地与任何其他 HTTP 网络库集成。 要使用 goproxy,需要将浏览器(或任何其他客户端)设置为使用 goproxy 作为 HTTP 代理。 以下是在 [Chrome](https://www.wikihow.com/Connect-to-a-Proxy-Server) 和 [Firefox](http://www.wikihow.com/Enter-Proxy-Settings-in-Firefox) 中的设置方法。 如果您决定从 `base` 示例开始,用作代理的 URL 是 `localhost:8080`,这是我们示例中的默认值。 您还需要[信任](https://github.com/elazarl/goproxy/blob/master/examples/customca/README.md)代理 CA 证书,以避免客户端出现任何证书问题。 > [✈️ Telegram 群组](https://telegram.me/goproxygroup) > > [🎁 成为赞助商](https://opencollective.com/goproxy) ## 功能特性 - 仅对`特定主机`执行某些操作,可通过单一相等比较或正则匹配实现 - 在将`请求`和`响应`发送到浏览器之前对其进行操作 - 使用`自定义 http.Transport`向目标服务器发起请求 - 您可以指定一个`MITM 证书缓存`,以便稍后对同一主机的其他请求复用,从而节省 CPU。默认未启用,但您应该在生产环境中使用它! - 当目标是`相对路径`(例如 `/ping`)时,将常规 HTTP 流量重定向到`自定义处理器` - 您可以通过实现 `Logger` 接口来选择使用的日志记录器 - 通过将 `PreventCanonicalization` 设置为 true,可以`禁用` HTTP 请求头的`规范化` ## 代理模式 1. 常规 HTTP 代理 2. 通过 CONNECT 的 HTTPS 3. HTTPS MITM("中间人")代理服务器,其中服务器生成 TLS 证书来解析请求/响应数据并对其执行操作 4. "劫持"代理连接,配置的处理器可以访问原始 net.Conn 数据 ## 赞助商 您的公司使用 GoProxy 吗?请帮助我们保持项目的维护和健康发展! 支持 GoProxy 可以让我们投入更多时间进行 bug 修复和新功能开发。 作为回报,如果您选择 Gold Supporter 或 Enterprise 计划,我们将在此处自豪地展示贵公司的 Logo。 > [成为赞助商](https://opencollective.com/goproxy) [](https://opencollective.com/goproxy) [](https://opencollective.com/goproxy) ## 维护者 - [Elazar Leibovich](https://github.com/elazarl):项目创建者,软件工程师 - [Erik Pellizzon](https://github.com/ErikPelli):维护者,自由职业者(欢迎合作!) 如果您需要将 GoProxy 集成到您的项目中,或者您需要在分叉中维护一些自定义功能,您可以通过电子邮件联系 [Erik](mailto:[email protected])(现任维护者),共同讨论他如何以付费独立顾问的身份为您提供帮助。 ## 贡献 如果您遇到任何问题、有建议,或者发现了 bug,欢迎通过提交 GitHub `issue` 与我们联系。 这是一个由志愿者管理的`开源`项目,我们很乐意讨论任何可以改进它的内容。 请务必解释清楚一切,包括问题背后的原因以及您想要更改的内容,以便更容易理解问题。 如果是小的代码更改,您也可以直接提交 `Pull Request`,但需要在描述中说明一切。 如果您提交一个名为 `refactoring` 且改动 `5,000` 行的 Pull Request,我们不会合并它……`:D` 本项目的代码以 `BSD 3-Clause` 许可证发布,因此也适用于`商业`用途。 ### 提交您的案例研究 那么,您已经将 GoProxy 引入并集成到您的个人项目或您所在公司的项目中了。 我们很高兴了解使用这个库构建的新`创意解决方案`,因此欢迎通过电子邮件`联系`上面列出的维护者,说明您为什么认为这个项目对您的需求很有用。 如果您与公司签署了`保密协议`,您可以建议他们在其官方网站上撰写一篇关于此主题的`博客文章`,这样该信息将由他们自行决定公开,您也可以与我们`分享博客文章的链接`:) 案例研究的目的是与`社区`分享:为什么这个项目的所有`贡献者`都在通过他们的帮助`改善`世界,以及人们正在使用它构建什么。 ### Linter 代码库会对您的 Pull Request 代码进行自动 lint 检查。 在提交之前,您应该在本地机器上运行 linter,检查您的更改是否符合规范,这样就不会有任何意外。 要安装 linter: ```sh go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest ``` 这将在您的 `$GOPATH/bin` 文件夹中创建一个可执行文件(`$GOPATH` 是一个环境变量,通常其值相当于 `~/go`,如果您不确定,请检查您机器上的值)。 请确保将 bin 文件夹包含在 shell 的路径中,以便能够直接使用 `golangci-lint run` 命令。 ## GoProxy 初体验 为了体验 `goproxy`,这里有一个基本的 HTTP/HTTPS 代理,它只是将数据转发到目标地址: ```go package main import ( "log" "net/http" "github.com/elazarl/goproxy" ) func main() { proxy := goproxy.NewProxyHttpServer() proxy.Verbose = true log.Fatal(http.ListenAndServe(":8080", proxy)) } ``` ### 请求处理器 这一行将为所有通过代理发送的请求添加 `X-GoProxy: yxorPoG-X` 请求头,然后再发送到目标地址: ```go proxy.OnRequest().DoFunc( func(r *http.Request,ctx *goproxy.ProxyCtx)(*http.Request,*http.Response) { r.Header.Set("X-GoProxy","yxorPoG-X") return r,nil }) ``` 当 `OnRequest()` 的输入为空时,`DoFunc` 中指定的函数将处理所有到达代理的请求。在这种情况下,它会为请求添加一个请求头并将其返回给调用方。 代理会将修改后的请求发送到目标地址。 如果您在您的类型中实现了指定的接口,也可以使用 `Do` 而不是 `DoFunc`。 > ⚠️ 请注意,我们返回了一个 nil 值作为响应。 > 如果返回的响应不为 nil,goproxy 将丢弃该请求, > 并将指定的响应发送给客户端。 ### 条件请求处理器 在服务器本地时区的 8 点到 17 点之间拒绝连接到 www.reddit.com: ```go proxy.OnRequest(goproxy.DstHostIs("www.reddit.com")).DoFunc( func(req *http.Request,ctx *goproxy.ProxyCtx)(*http.Request,*http.Response) { if h,_,_ := time.Now().Clock(); h >= 8 && h <= 17 { resp := goproxy.NewResponse(req, goproxy.ContentTypeText, http.StatusForbidden, "Don't waste your time!") return req, resp } return req, nil }) ``` `DstHostIs` 返回一个 `ReqCondition`,它是一个接收 `*http.Request` 并返回布尔值的函数,用于检查请求是否满足条件(如果满足则会被处理)。 当请求指向 "www.reddit.com" 时,`DstHostIs("www.reddit.com")` 将返回一个返回 true 的 `ReqCondition`。 主机相等性检查是`不区分大小写`的,以反映 DNS 解析器的行为,因此即使用户输入 "www.rEdDit.com",该比较也会满足条件。 当时间在上午 8:00 到下午 5:59 之间时,我们直接在 `DoFunc()` 中返回一个响应,这样远程目标将不会收到该请求,客户端将收到 `"Don't waste your time!"` 响应。 ### 让我们开始 ```go import "github.com/elazarl/goproxy" ``` `examples` 文件夹中有一些代理使用示例,涵盖了最常见的用例。看一看,祝你好运! ## 请求与响应操作 有 3 种不同类型的处理器来操作代理的行为,如下所示: ```go // handler called after receiving HTTP CONNECT from the client, and // before proxy establishes connection with the destination host httpsHandlers []HttpsHandler // handler called before proxy sends HTTP request to destination host reqHandlers []ReqHandler // handler called after proxy receives HTTP Response from destination host, // and before proxy forwards the Response to the client respHandlers []RespHandler ``` 根据您想要操作的内容,向上述每个列表添加处理器的方式如下: ```go // Add handlers to httpsHandlers proxy.OnRequest(some ReqConditions).HandleConnect(YourHandlerFunc()) // Add handlers to reqHandlers proxy.OnRequest(some ReqConditions).Do(YourReqHandlerFunc()) // Add handlers to respHandlers proxy.OnResponse(some RespConditions).Do(YourRespHandlerFunc()) ``` 示例: ```go // This rejects the HTTPS request to *.reddit.com during HTTP CONNECT phase. // Reddit URL check is case-insensitive because of (?i), so the block will work also if the user types something like rEdDit.com. proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("(?i)reddit.*:443$"))).HandleConnect(goproxy.AlwaysReject) // Be careful about this example! It shows you a common error that you // need to avoid. // This will NOT reject the HTTPS request with URL ending with .gif because, // if the scheme is HTTPS, the proxy will receive only URL.Hostname // and URL.Port during the HTTP CONNECT phase. proxy.OnRequest(goproxy.UrlMatches(regexp.MustCompile(`.*gif$`))).HandleConnect(goproxy.AlwaysReject) // To fix the previous example, here there is the correct way to manipulate // an HTTP request using URL.Path (target path) as a condition. proxy.OnRequest(goproxy.UrlMatches(regexp.MustCompile(`.*gif$`))).Do(YourReqHandlerFunc()) ``` ## 错误处理 ### 通用错误 如果在通过代理处理请求时发生错误,默认情况下代理会返回 HTTP 错误 `500`(内部服务器错误),并将`错误消息`作为`响应体`内容。 如果您想覆盖此行为,可以定义自己的 `RespHandler` 来更改错误响应。 在上下文参数中,`ctx.Error` 包含发生的 `error`(如果有),如果没有发生错误,则为 `nil` 值。 您可以按自己的意愿处理它,包括返回自定义 JSON 作为响应体。 错误处理器示例: ``` proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response { var dnsError *net.DNSError if errors.As(ctx.Error, &dnsError) { // Do not leak our DNS server's address dnsError.Server = "<server-redacted>" return goproxy.NewResponse(ctx.Req, goproxy.ContentTypeText, http.StatusBadGateway, dnsError.Error()) } return resp }) ``` ### 连接错误 如果在向目标远程服务器(或代理客户端)发送数据时发生错误,将调用 `proxy.ConnectionErrHandler` 来处理该错误(如果存在),否则将使用`默认处理器`。 错误作为`函数参数`传递,而不是放在代理上下文中,因此您不必在此处理器中检查 ctx.Error 字段。 在此处理器中,您可以访问与代理客户端的原始连接(作为 `io.Writer`),因此如果需要,您可以通过它发送任何包含错误数据的 HTTP 数据。 无法保证连接尚未被关闭,因此 `Write()` 可能返回错误。 在错误处理器调用之后,代理库将`自动关闭`该`连接`,因此您不必担心这一点。 ## 项目状态 这个项目创建于`10年`前,已经达到了`成熟`阶段。它可以安全地用于`生产环境`,许多项目已经在这样做了。 如果未来有任何`破坏性变更`,将发布 Go 模块的`新版本`(例如 v2)。 ## 受以下项目信任,并作为其直接依赖: <p align="left"> <a href="https://github.com/stripe/goproxy" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/64d9d4a11b59a2883beada1d0e2d5e574327f693a7b84f0905510f865248f63e/649c74ea103584e65478fd86f61a32c4651855d53efb8b8d9b9011b42e39c4ee-display-v1.webp" alt="Stripe" title="Stripe" /> </a> <a href="https://github.com/dependabot/goproxy" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/537c51643f1d6066d041dba12f4bcae952c41490dcf6e6a1143a2e2b15d82199/ec116e30794b65255c125251a815dc4dd376fbdd76a6919fe1d2decae4c8429d-display-v1.webp" alt="Dependabot" title="Dependabot" /> </a> <a href="https://github.com/go-git/go-git" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/141e8059d0f465d80548bbe9af30697989ed963c30581830b97bc57ef15da0d5/fd51665ff118904f4eefb78cfd2774c195fdf100cffaa6c03e4b8467584c42bd-display-v1.webp" alt="Go Git" title="Go Git" /> </a> <a href="https://github.com/google/oss-rebuild" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/3cdb183f5b49d7315445abe5fd1e1dac0665db8ad88ef05062eea726ae908031/1957e79f54e85ce7afc6febabb41556f30f81b172a0c63688094ca62515817a1-display-v1.webp" alt="Google" title="Google" /> </a> <a href="https://github.com/grafana/grafana-plugin-sdk-go" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/801cf1f9b90012f77d2cdbac224be8b5d7def3b5b97483bedaeca069dad28790/c68471eb91d68e700faf0b225cb7f5eb55b88e520068ede25e660bfcca0f7681-display-v1.webp" alt="Grafana" title="Grafana" /> </a> <a href="https://github.com/superfly/tokenizer" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/fc6176b4a42fa9a431e616d58461b2b6d9fcc84ac214f1f1d321527a6445ee12/b10213639c5ce30276ff67a0f4609737b8c6a65b76b2d99d23805892a99e79d6-display-v1.webp" alt="Fly.io" title="Fly.io" /> </a> <a href="https://github.com/kubernetes/minikube" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/3ea12262ac6217219b5cffb4fbc2b06d415dcee86a86e9ff620fa3369a64ae36/0ef3dfd53535365fca209291742bdd27099f430199526b20ba59f56c180fcc7e-display-v1.webp" alt="Kubernetes / Minikube" title="Kubernetes / Minikube" /> </a> <a href="https://github.com/newrelic/newrelic-client-go" target="_blank" rel="noreferrer"> <img src="https://assets.kitploit.com/production/public/readmes/50732/e3060fc9e303c90a833c7a6e01c4977d237a503215c5d6da66817881de9298c3/36b33aedf9fdd68f8e3ff5e8e9274cad40fb63d874187000c2dd29edc533d02f-display-v1.webp" alt="New Relic" title="New Relic" /> </a> </p>