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

如何使用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)
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题