【问题标题】:how to proxy GET request in golang with URL manipulation如何通过 URL 操作在 golang 中代理 GET 请求
【发布时间】:2018-06-15 23:36:49
【问题描述】:

我想构建一个 golang 服务,它会监听 GET 请求,进行一些 URL 操作,然后将一个新请求(到被操作的 URL)代理回浏览器:

(从浏览器 -> 服务器)GET http://www.example.com/7fbsjfhfh93hdkwhfbf398fhkef93..

(服务器操纵 URL - 解密“7fbsjfhfh93hdkwhfbf398fhkef93..” -> “my-super-resource”)

(服务器 -> URL 资源)GET http://www.somewhereelse.com/my-super-resource

(服务器 -> 浏览器)来自http://www.somewhereelse.com/my-super-resource 的响应传递给浏览器(使用 cors)

整个链需要同步,这没关系。是否有一个体面的代理库来支持这种事情?

【问题讨论】:

  • 这不适用于标准库ReverseProxy
  • 您也可以只使用标准http.HandlerFunc,接收请求,对请求执行某些操作,然后使用Sling 之类的包发出另一个请求,等待响应,然后使用该响应将响应发送回原始请求。这也为您提供了代理行为,并且不太依赖于任何类型的“框架”方法。另外,我非常怀疑你会找到任何可以让你精确地完成你详细描述的事情的东西。这是非常具体的......您可能需要编写一些如上所述的自定义代码。

标签: go


【解决方案1】:

您可以使用 Sling 包在不到 10 行代码中完成类似的操作:

type Foo struct {
    Bar string `json:"bar"`
}

func Handler(w http.ResponseWriter, r *http.Request) {
    // Get the URL and decrypt it
    url := getUrl(r)
    decryptedUrl := decryptUrl(url)

    // Use the decrypted URL to make a request to another service
    var data *Foo
    req, err := sling.New().Get(decryptedUrl).Receive(data)
    if err != nil {
         // Handle error...
    }

    // Respond to the original request using the data from the other service
    respond(w, http.StatusOK, data)
}

【讨论】:

  • 这当然没有反向代理语义。对于初学者,有趣的请求标头和响应标头都没有传递。
  • 是的。然而,这更像是他如何实现类似功能的蓝图。他可以对其进行更多自定义并传递标题等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 2012-09-18
  • 2022-07-13
  • 2021-12-25
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多