ds15812330851 2018-06-15 15:12
浏览 82
已采纳

如何使用URL操作在golang中代理GET请求

I want to build a golang service which will listen for GET request, do some URL manipulation and then proxy a new request (to the manipulated URL) back to the browser:

(from browser -> server) GET http://www.example.com/7fbsjfhfh93hdkwhfbf398fhkef93..

(server manipulates URL - decrypts "7fbsjfhfh93hdkwhfbf398fhkef93.." -> "my-super-resource")

(server -> URL resource) GET http://www.somewhereelse.com/my-super-resource

(server -> browser) Response from http://www.somewhereelse.com/my-super-resource passed on to browser (using cors)

The whole chain will need to be synchronous which is ok. Is there a decent proxy library which allows for this sort of thing?

  • 写回答

1条回答 默认 最新

  • dsuw85815 2018-06-15 15:36
    关注

    You can do something like this in less than 10 lines of code with the Sling package:

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题